Why does HTML Canvas getImageData() not return the exact same values that were just set?

后端 未结 3 682
暖寄归人
暖寄归人 2020-11-30 05:40

When writing pixels to an HTML Canvas context using putImageData I find that the pixel values are not exactly the same when I fetch them again. I have put up a

3条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-30 06:19

    HTML5 specification encourages browser vendors to use something that is called Premultiplied Alpha. In essence this means that pixels are stored in 32-bit integers where each channel contains a 8-bit color value. For performance reasons, the Premultiplied Alpha is used by browsers. What it means is that it premultiplies color values based on the alpha value.

    Here's an example. You have a color such that the values for RGB are 128, 64, 67. Now, for the sake of higher performance, the color values will be premultiplied by the alpha value. So, in case the alpha value is 16, all the color values will get multiplied by 16/256 (= 0.0625). In this case, the resulting values for RGB become 8, 4, 4.1875 (rounded to 4 because pixel color values are not floats).

    The problem shows up when you do exactly what you are doing here; setting color data with a specific alpha value and then pulling back the actual color values. The previous Blue color of 4.1875 that got rounded to 4 will become 64 instead of 67 when you call getImageData().

    That is why you are seeing all this and it will never change unless the underlying implementation in a browser engine changes to use a color system that does not suffer from this.

提交回复
热议问题