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

164
Vistas
Why does getImageData round RGBA values?

The following code intends to set the canvas background color to rgba(16,0,0,0.1), with an expected output of [16,0,0,26], assuming an alpha value of 0.1 is equivalent to an ImageData byte of 26:

var canvas = document.createElement('canvas');
var ctx = canvas.getContext("2d");
ctx.fillStyle = "rgba(16, 0, 0, 0.1)";
ctx.fillRect(0, 0, 50, 50);
var output = ctx.getImageData(0, 0, 1, 1).data;
console.log(output.toString(16));

However, instead of [16,0,0,26], we get [20,0,0,26]. Somehow, a color value has inexplicably changed. If RGBA values are being stored correctly, this shouldn't occur, right?

Consider this second example, where we set a pixel value directly:

var canvas = document.createElement('canvas');
var ctx = canvas.getContext("2d");
var imgData = ctx.createImageData(50, 50);

imgData.data[0] = 16;
imgData.data[1] = 0;
imgData.data[2] = 0;
imgData.data[3] = 26;

ctx.putImageData(imgData, 0, 0);
var output = imgData.data;
console.log(output.slice(0,4).toString());

Now it correctly retrieves [16,0,0,26]. However, if output = ctx.getImageData(0, 0, 1, 1).data is used instead, we again get [20,0,0,26]. So this suggests getImageData is doing something wrong, corrupting our color values.

So, why 20? It seems to be directly related to the alpha channel. As opacity decreases, the RGB values appear to become less precise than what they should, almost as if the color is being converted to RGB and then back to RGBA again. In fact, this may not be far from the truth, as the cause appears to be related to rounded alpha composition math:

// Divide alpha value
var A = 26 / 255;  // 0.10196078431372549
var C = 16 * A;    // 1.6313725490196078
C = Math.round(C); // rounding should not occur
C = C / A;         // 19.615384615384617
C = Math.round(C); // rounding should not occur

Here's some simulation code showing that this kind of rounded conversion largely represents what getImageData is doing.

So why does this occur in both Firefox and Chrome? Is this a bug that's gone unnoticed for years, or very odd, but intentional behavior? If this is intentional behavior, why is it this way, and how can one work around it?

about 4 years ago · Juan Pablo Isaza
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