Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

264
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda