Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

262
Views
trying to create a little color picker, why is context.getImageData() returning only zeros when i use flex display in css?

i created a gradient in javascript,

var colorCanvas = document.getElementById('color_canvas');
var ColorCtx = colorCanvas .getContext('2d');

var color = 'rgba(0,0,255,1)';
    let gradientH = ColorCtx .createLinearGradient(0, 0, ColorCtx.canvas.width, 0);
    gradientH.addColorStop(0, '#fff');
    gradientH.addColorStop(1, color);
    ColorCtx .fillStyle = gradientH;
    ColorCtx .fillRect(0, 0, ColorCtx.canvas.width, ColorCtx.canvas.height);

    let gradientV = ColorCtx .createLinearGradient(0, 0, 0, 300);
    gradientV.addColorStop(0, 'rgba(0,0,0,0)');
    gradientV.addColorStop(1, '#000');
    ColorCtx .fillStyle = gradientV;
    ColorCtx .fillRect(0, 0, ColorCtx.canvas.width, 
    ColorCtx .canvas.height); 

the above creates a gradient.

colorCanvas.addEventListener('click',function(event){
    let x = event.clientX; 
    let y = event.clientY; 
    pixel = ColorCtx.getImageData(x,y,1,1);   // Read pixel Color
    let rgb = `rgba(${pixel.data[0]},${pixel.data[1]},${pixel.data[2]},${pixel.data[3]})`;
    console.log(rgb);
    document.getElementById('pick').style = 'background-color: ' + rgb;
    document.querySelector('.picked-color').style = 'background-color: ' + rgb;

});

the event listener is suppose to pick a color from mouse position and make it the background color of the two divs

document.getElementById('pick').style = 'background-color: ' + rgb;
document.querySelector('.picked-color').style = 'background-color: ' + rgb;

but the pixel = ColorCtx.getImageData(x,y,1,1); only returns an array of zeros

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Figured it out my self,

let rect = event.target.getBoundingClientRect();
    let x = event.clientX - rect.left; // x position within the element.
    let y = event.clientY - rect.top; // y position within the element

Figured I was trying to get the mouse position but not within the intended element, thats why the color picker was not working, with the code above included, it works as I intended.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!