javascriptgetimagedata

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


Solution

  • 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.