Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

263
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda