Flood fill using color picker in javaScript

I’m working on a paint app that has multiple tools (pen, eraser…etc.) and I created a flood fill tool. The code below fills according to colourPalette inputs. I’m trying to use a color picker to pick the color of the fill. How can I adapt the following code to do so?

there’s the colourPalette function that has r,g,b,a as arguments and I think that’s the problem
I created a color picker but the problem is linking it to the tool

var d;
    function FillBucketTool()
    {
        let self = this;
        d = pixelDensity();
      //set an icon and a name for the object
      self.icon = 'assets/fillBucket.png';
      self.name = 'fillBucketTool';
      self.colour = ColourPalette(0,0,100,100);
    
    //create div and picker for tool
//    self.colorPara = createDiv('Fill Color').position(985,943).class('box options').style('font-size', '30px');
//    self.fillColorPicker = createColorPicker().parent(self.colorPara).style('margin: 10px; width: 70px');
//    self.colour = ColourPalette(self.fillColorPicker.value(),255);
    
  self.draw = function () {
    if (mouseIsPressed) {
      floodFill(mouseX, mouseY);
    }
  };

  self.setColour = function (col) {
    self.colour = col;
  };

  function matchColour (pos, oldColour) {
    var current = getPixelData(pos.x, pos.y);
    return (   current[0] === oldColour[0] && current[1] === oldColour[1] 
            && current[2] === oldColour[2] && current[3] === oldColour[3] );
  }

  function getKey (pos) {
    return ""+pos.x+"_"+pos.y;
  }

  function checkPixel(pos, positionSet) { 
    return ! positionSet.hasOwnProperty( getKey(pos) );
  }

  function floodFill (xPos, yPos) {

    var stack = [];
    var pixelList = {};

    var first = {'x':xPos,'y':yPos};
    stack.push( first );
    pixelList[ getKey(first) ] = 1;

    loadPixels();
    var firstColour = getPixelData(xPos, yPos);

    while (stack.length > 0) {

      var pos1 = stack.pop();

      setPixelData(pos1.x, pos1.y, self.colour);

      var up = {'x':pos1.x,  'y':pos1.y-1};
      var dn = {'x':pos1.x,  'y':pos1.y+1};
      var le = {'x':pos1.x-1,'y':pos1.y};
      var ri = {'x':pos1.x+1,'y':pos1.y};

      if (0 <= up.y && up.y < height && matchColour(up, firstColour)) addPixelToDraw(up);
      if (0 <= dn.y && dn.y < height && matchColour(dn, firstColour)) addPixelToDraw(dn);
      if (0 <= le.x && le.x < width  && matchColour(le, firstColour)) addPixelToDraw(le);
      if (0 <= ri.x && ri.x < width  && matchColour(ri, firstColour)) addPixelToDraw(ri);
    }

    updatePixels();
      
    function addPixelToDraw (pos) {

      if (checkPixel(pos, pixelList)  ) {
        stack.push( pos );
        pixelList[ getKey(pos) ] = 1;
      }
    }
  }  

}


function ColourPalette (r,g,b,a) { 
  var self = (this !== window ? this : {});
  if (arguments.length === 0) {
    self['0'] = 0; self['1'] = 0; self['2'] = 0; self['3'] = 0;
  } else if (arguments.length === 1) {
    self['0'] = r[0]; self['1'] = r[1]; self['2'] = r[2];  self['3'] = r[3]; 
  } else if (arguments.length === 4) {
    self['0'] = r; self['1'] = g; self['2'] = b; self['3'] = a;
  } else {
    return null;
  }
  return self;
}

function getPixelData (x, y) {
  var colour = [];
  for (var i = 0; i < d; ++i) {
    for (var j = 0; j < d; ++j) {
      let idx = 4 * ((y * d + j) * width * d + (x * d + i));
      colour[0] = pixels[idx];
      colour[1] = pixels[idx+1];
      colour[2] = pixels[idx+2];
      colour[3] = pixels[idx+3];
    }
  }
  return colour;
}

function setPixelData (x, y, colour) {
  for (var i = 0; i < d; ++i) {
    for (var j = 0; j < d; ++j) {
      let idx = 4 * ((y * d + j) * width * d + (x * d + i));
      pixels[idx]   = colour[0];
      pixels[idx+1] = colour[1];
      pixels[idx+2] = colour[2];
      pixels[idx+3] = colour[3];
    }
  }
}

XMLHttpRequest FormData not submitting data

I am trying to submit a form using the post method and a FormData object. I annotated my servlet with @MultipartConfig but it doesnt work

js

async function addAuthors() {
        let xhr = new XMLHttpRequest();
        const form = document.getElementById( "authorForm" );
        const FD = new FormData(form);
        xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        xhr.open("POST", "http://localhost:8081/Task1_war/main?command=addAuthor");
        xhr.send(FD);
} 

html

   <form id="authorForm">
        <Label>Author (required)</Label>
        <input type="text"  name="authorName" class="req"/>
        <label class="errorInput"  ></label>
        <Label>Author image></Label>
        <input type="file" id="authorImage" name="path" accept=".jpg,.png,.jpeg ">

    </form>
    <div class="add" onclick="addAuthors()">Send</div>

API host’s rate-limit header not read properly

Here is my code:

const timer = ms => new Promise(resolve => setTimeout(resolve, ms));

const createThrottler = (limitHeader) => {
  let requestTimestamp = 0;
  let rateLimit = 0;
  return (requestHandler) => {
    return async (...params) => {
      const currentTimestamp = Number(Date.now());
      if (currentTimestamp < requestTimestamp + rateLimit) {
        const timeOut = rateLimit - (currentTimestamp - requestTimestamp);
        requestTimestamp = Number(Date.now()) + timeOut;
        await timer(timeOut)
      }
      requestTimestamp = Number(Date.now());
      const response = await requestHandler(...params);
      if (!rateLimit > 0) {
        rateLimit = Math.floor((60 / response.headers.get(limitHeader)) * 1000);
      }
      console.log(limitHeader);
      console.log(rateLimit);
      return response;
    }
  }
}

const throttle = createThrottler("X-***-Ratelimit");
const throttleFetch = throttle(fetch);

function getRelease(idFiltered) {
  return throttleFetch(`https://api.***.com/releases/${idFiltered}`, {
    headers: {
      'User-Agent': '***/0.1',
    },
  }).then(response => response.json())
    .then(data => {
      if (data.message === 'Release not found.') {
        return { error: `Release with ID ${idFiltered} does not exist` };
      } else {
        const id = data.id;
        const delimiter = document.getElementById("delimiter").value || "|";
        const artists = data.artists ? data.artists.map(artist => artist.name) : [];
        const barcode = data.identifiers.filter(id => id.type === 'Barcode')
          .map(barcode => barcode.value);
        var formattedBarcode = barcode.join(delimiter);
        const country = data.country || 'Unknown';
        const genres = data.genres || [];
        const formattedGenres = genres.join(delimiter);
        const labels = data.labels ? data.labels.map(label => label.name) : [];
        const formattedLabels = labels.join(delimiter);
        const catno = data.labels ? data.labels.map(catno => catno.catno) : [];
        const formattedCatNo = catno.join(delimiter);
        const styles = data.styles || [];
        const formattedStyles = styles.join(delimiter);
        const tracklist = data.tracklist ? data.tracklist
          .map(track => track.title) : [];
        const formattedTracklist = tracklist.join(delimiter);
        const year = data.year || 'Unknown';
        const format = data.formats ? data.formats.map(format => format.name) : [];
        const qty = data.formats ? data.formats.map(format => format.qty) : [];
        const descriptions = data.formats ? data.formats
          .map(descriptions => descriptions.descriptions) : [];
        const preformattedDescriptions = descriptions.toString()
          .replace('"', '""').replace(/,/g, ', ');
        const formattedDescriptions = '"' + preformattedDescriptions + '"';
        console.log(idFiltered,
          artists,
          format,
          qty,
          formattedDescriptions,
          formattedLabels,
          formattedCatNo,
          country,
          year,
          formattedGenres,
          formattedStyles,
          formattedBarcode,
          formattedTracklist
        )

        return [idFiltered,
          artists,
          format,
          qty,
          formattedDescriptions,
          formattedLabels,
          formattedCatNo,
          country,
          year,
          formattedGenres,
          formattedStyles,
          formattedBarcode,
          formattedTracklist
        ];
      }
    });
}

But the “X-***-Ratelimit” header is clearly not being read correctly, as when I do

      console.log(limitHeader);
      console.log(rateLimit);

I initially get back

object

and thereafter

X-***-Ratelimit
Infinity

From the host’s documentation:

We attach the following headers to responses to help you track your rate limit use:

X-***-Ratelimit: The total number of requests you can make in a one minute window.

X-***-Ratelimit-Used : The number of requests you’ve made in your existing rate limit window.

X-***-Ratelimit-Remaining: The number of remaining requests you are able to make in the existing rate limit window.

Any help please? TIA.

On click only works once

for my responsive (mobile) hamburger-menu, i wanted to show the menu, when a class is pressed.
But it only works once (‘click’ is only locked once in the console, so it doesn’t register the clicks after it was pressed one time).
My JS code:

var btn = document.querySelector(".toggle-btn");
var navbar = document.querySelector(".menue");



btn.addEventListener('click', () =>{
    console.log('click');
    navbar.classList.toggle("active");
})

My html code:

<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">

<div class="nav-bar">
    <nav>
        <div class="logo">
            <a href="../../index.php"><img src="../png/lg_nord_logo_navbar.png" alt=""></a>
        </div>
        <a href="#" class="toggle-btn">
            <span class="bar"></span>
            <span class="bar"></span>
            <span class="bar"></span>
        </a>
        <div class="menue">
            <ul>
                <li><a href="#">Disziplinen</a>
                    <ul>
                        <li><a href="../disziplinen/30_m_startblock.php">30 meter startblock</a></li>
                        <li><a href="../disziplinen/30_m_fliegend.php">30 meter fliegend</a></li>
                        <li><a href="../disziplinen/60m.php">60 meter</a></li>
                        <li><a href="../disziplinen/10er_hopserlauf.php">10er Hopserlauf</a></li>
                        <li><a href="../disziplinen/Klappmesser.php">Klappmesser</a></li>
                        <li><a href="../disziplinen/Klimmzuege.php">Klimmzüge</a></li>
                        <li><a href="../disziplinen/liegestuetze.php">Liegestütze</a></li>
                        <li><a href="../disziplinen/standweitsprung.php">Standweitsprung</a></li>
                    </ul>
                </li>
                <li><a href="#">Daten hinzufügen</a>
                    <ul>
                        <li><a href="../addData/30_m_startblock.php">30 meter startblock</a></li>
                        <li><a href="../addData/30_m_fliegend.php">30 meter fliegend</a></li>
                        <li><a href="../addData/60m.php">60 meter</a></li>
                        <li><a href="../addData/10er_hopserlauf.php">10er Hopserlauf</a></li>
                        <li><a href="../addData/Klappmesser.php">Klappmesser</a></li>
                        <li><a href="../addData/Klimmzuege.php">Klimmzüge</a></li>
                        <li><a href="../addData/liegestuetze.php">Liegestütze</a></li>
                        <li><a href="../addData/standweitsprung.php">Standweitsprung</a></li>
                    </ul>
                </li>
                <li><a href="#"><i class="material-icons">support_agent</i>Athleten (beta)</a>
                    <ul>
                        <li><a href="../athlet_search/index.php?name=tom">Tom-Luca</a></li>
                        <li><a href="../athlet_search/index.php?name=marc">Marc          </a></li>
                        <li><a href="../athlet_search/index.php?name=leo">Leo          </a></li>
                        <li><a href="../athlet_search/index.php?name=lukas">Lukas</a></li>
                        <li><a href="../athlet_search/index.php?name=vincent">Vincent</a></li>
                        <li><a href="../athlet_search/index.php?name=damien">Damien</a></li>
                        <li><a href="../athlet_search/index.php?name=karsten">Karsten</a></li>
                    </ul>
                </li>
                <li><a href="../../settings/"><i class="material-icons">admin_panel_settings</i> Einstellungen</a></li>
                <li><a class="state" href="login.php">Login</a></li>
                <li><a href="../logout.php"><i class="fas fa-sign-out-alt"></i>  Logout</a></li>
            </ul>
        </div>
    </nav>
</div>

What is my mistake? Thank you for your advice!

window.screen.width do not work on ios devices?

I have sphere animation on my site, for laptop, tablet and mobile I m using different sizes of sphere. Here you can see conditions of every type of device:

Laptop:
var screen_size = window.screen.width;
if(screen_size < 1025){
    false;
}else{
    sphere animation code;
}
Tablet:
var screen_size = window.screen.width;
if(screen_size >= 1025  || screen_size  < 668){
    false;
}else{
    sphere animation code;
}
Mobile:
var screen_size = window.screen.width;
if((screen_size > 667)){
    false;
}else{
    sphere animation code;
}

If I use one script separately its – works, other operation system – its works. I think suppose main problem in “window.screen.width”.

Here you an see my site with full code: thesevenwang

Trying to read request but getting Request {}

I am trying to work with an api but I can’t get the result of the request:

async function user(id) {
  let req = new Request(`https://api.clashroyale.com/v1/players/%23${id}`)
  req.method = "GET";
  req.headers = {"authorization": `Bearer ${token}`}
  let json = await req
  console.log(json)
}

It returns

Request {}

How can I get the content of the response?

I need to get sequence of 20 records for Ag-Grid React Js from javaScript object, instead of fetching from json server (url) while i scroll down

I am Implementing Ag-grid for infinite scrolling, the problem I am facing is when we hit API for data it returns all data. what I want is that if we scroll down it then hit API to bring the next data. But in ag-grid, all data comes in sequence of 20 rows and saves in our browser memory.

i have json data as js objects, need to get sequences of 20 data from object in js, instead of fetching from url.

import React, { useState } from 'react'
import { AgGridReact } from 'ag-grid-react';
import 'ag-grid-enterprise';
import 'ag-grid-community/dist/styles/ag-grid.css';
import 'ag-grid-community/dist/styles/ag-theme-alpine.css';
import {data} from './data'

const App = () => {
  const [gridApi, setGridApi] = useState(null);

  const columns = [
    { headerName: "Athlete", field: "athlete", filter: "agTextColumnFilter", cellRenderer: 'Loading' },
    { headerName: "Age", field: "age", filter: "agTextColumnFilter" },
    { headerName: "Country", field: "country", filter: "agTextColumnFilter" },
    { headerName: "Year", field: "year", filter: "agTextColumnFilter" },
    { headerName: "Date", field: 'date', filter: "agTextColumnFilter" },
    { headerName: "Sport", field: 'sport', filter: "agTextColumnFilter" },
    { headerName: "Gold", field: 'gold', filter: "agTextColumnFilter" },
    { headerName: "Silver", field: 'silver', filter: "agTextColumnFilter" },
    { headerName: "Bronze", field: 'bronze', filter: "agTextColumnFilter" },
    { headerName: "Total", field: 'total', filter: "agTextColumnFilter" },
  ]
  const datasource = {
    getRows(params) {
      console.log(JSON.stringify(params, null, 1));
      const { startRow, endRow}= params
      // let url = `http://localhost:3001/olympic?`
     
      //Pagination 
      url += `_start=${startRow}&_end=${endRow}`
      fetch(data)
        .then(httpResponse => httpResponse.json())
        .then(response => {
          params.successCallback(response, 499);
        })
        .catch(error => {
          console.error(error);
          params.failCallback();
        })
    }
  };

  const onGridReady = (params) => {
    setGridApi(params);
    // register datasource with the grid 
    params.api.setDatasource(data);
  }


  const components = {
    Loading: (params) => {
      if (params.value !== undefined) {
        return params.value
      } else {
        return "Loading .. "
      }
    }
  }

  return (
    <div>
      <h1 align="center">Trial Scroll</h1>
      <div className="ag-theme-alpine" style={{ height: 800 }}>
        <AgGridReact
          columnDefs={columns}
          rowModelType="infinite"
          onGridReady={onGridReady}
          cacheBlockSize={20}
          rowData={data}
        />
      </div>
    </div>
  );
};
export default App 

here i tried to get data on url from json server, but i need to get data from javascript object.

How to add dynamic Where queries in objection.js?

I have a table which has a global search bar that needs to trigger search for all fields like firstName, lastName, email and role.

Also have a dynamic filter which can have single or multiple filter like “firstName” or/And “lastName”

Obviously they need to be paginated.

For pagination i can use Model.query().page(1, 10)

But how to supply search or filter. assuming only search or filter active at a given time.

Search and filter both using LIKE. How to dynamically do this.

Web3js smart contract interaction gas and signing

So I can interact with a function within a smart contract.
I also know that to actually do the transaction I need something like this:

const contractObj = new web3.eth.Contract(abi, contractAddress)

const transaction= await contractObj .methods.NameofTheMethod(x).send({from:myAddress,gasLimit:value})

My question is: what is the next step? Because I put myAddress but I should sign this before send the transaction right?

Otherwise how will it be able to take the fee from the gas?

Web scrapping in Chrome Console- iterate over rows in mat-tab element

DISCLAIMER: I do not know JS, it is an assignment for my work.

I have been asked to withdraw scrape some data from a Google Marketing page using Chrome Console.

The HTML code I need to scrape looks like this:

The code in the console

I made the following code where I created a dictionary and then used document.Selector()to take the data but I only take it from one row.

var IntegrationDetails = [{}]

IntegrationDetails[0]["Property Name"] = document.querySelector("JSPath").innerText

IntegrationDetails[0]["Advertiser"] = document.querySelector("JSPath").innerText

IntegrationDetails[0]["Tracking ID"] = document.querySelector("JSPath").innerText

IntegrationDetails[0]["Account"] = document.querySelector("JSPath").innerText

IntegrationDetails[0]["Organisation name"] = document.querySelector("JSPath").innerText

IntegrationDetails[0]["Integrations with reporting data"] = document.querySelector("JSPath").innerText

IntegrationDetails[0]["Integrations with Cost Data"] = document.querySelector("JSPath").innerText

IntegrationDetails[0]["Integrations with Remarketing Lists"] = document.querySelector("JSPath").innerText

copy(IntegrationDetails)

I do not know how to iterate over every row in the mat-tab element and append each row to the dictionary.

In React Js Axios request getting CROS error

I used Axios for API, here is my code. I am getting CROS error.

axios({
      method: 'GET',
      headers : { 'Content-Type': 'application/json',
                  'Access-Control-Allow-Origin' : '*',
                  'mode': 'cors',
                  'Authorization':'Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1N....'
                },
      url: baseURL,          
    }).then(function (response) {
          console.log(response);
    });

enter image description here

How to create a chart for showing sigma value like this

I need to create a stacked bar chart to show Six Sigma value as shown in the image

enter image description here

Here the values in the Y axis are static. But the values in the X axis are not evenly spaced. The image is not properly designed. I am attaching a picture to illustrate the values of the X axis according to the value of the bars. In the picture the yield column corresponds to the values on the bars.
enter image description here
Also I need to show the values on the bar as shown in the image.
I have tried to use chartjs 2 but I can not figure out how to make a custom spacing scale for the X axis.

My attempt at modifying the X axis ticks is given below

let chart = new Chart(ctx, {
  type: 'bar',
  data: {
    datasets: [{
      yAxisID: 'yAxis'
    }]
  },
  options: {
    scales: {
      xAxis: {
        type: 'logarithmic',
        position: 'right',
      }
    }
  }
});

Any recommendations other than chartjs for this functionality would also be highly appreciated

A text is displayed only right after my javascript is triggered

I wrote javascript codes.

By clicking the button, the child window pops up and displays a text sent from the parent window using a postMessage function.

My code could sent a text to the child window, but there’s no text displayed.
The text is displayed only when I keep clicking the button.

I think my code is overridden by a blank script or something, though I don’t write any other codes except for below.

Do you have any solution for this?

the parent window html

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>Parent Window</title>
</head>
<body>
  <input type="button" value="TEST_BUTTON" id="testButton">

  <script>
      var testButton = document.getElementById('testButton');
      testButton.addEventListener('click', function(event) {
        event.preventDefault();
        var newWindow = window.open('./child_window.html', 'popupWindow', 'width=400,height=300');
        newWindow.postMessage('this is a content from the parent window.', '*');
        return false;
      },false);
  </script>
</body>
</html>

the child window html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title>Pop Up Window</title>
  </head>
  <body>
    <h1 id="mainText"></h1>
    <script type="text/javascript">
      var mainText = document.getElementById('mainText');

      window.addEventListener('message', function(event) {
        console.log(event.data);
        this.mainText.innerText = event.data;
      }, false)
    </script>
  </body>
</html>

can we use js variable name as class name in html

I want to concatinate class name with variable count which keep getting updated after each button click, for which I am getting error as “citysName is null”. can anyone suggest

button.addEventListener('click', resp => {
    count = count +1;
    var card = document.createElement('card');
    card.innerHTML = `
                <img src="..." class="card-img-top" alt="...">
                <div class="card-body">
                  **<h5 class="card_title" + count></h5>
                  <h6 class="temp" + count></h6>
                  <p class="card-text" + count></p>**
                  <a href="#" class="btn-primary"></a>
                </div>
    `;
    card.className = 'card';
    var content = document.getElementById('id1');
    content.appendChild(card);
    **var citysName = document.querySelector('.card_title'+count);
    var description = document.querySelector('.card-text'+count);
    var temp = document.querySelector('.temp'+count);**
    fetch('https://api.openweathermap.org/data/2.5/weather?q='+inputVal.value+'&appid=a5599c020b0d897cbc8b52d547289acc')
    .then(post => post.json())
    .then(data => {
        var cityName = data['name'];
        var temper = data['main']['temp'];
        var descrip = data['weather'][0]['description'];

        let ctemp = Math.round(temper-273);
        citysName.innerHTML = cityName;
        temp.innerHTML = ctemp + "°C";
        description.innerHTML = descrip;
    })
})