Canvas PutImageData color loss with no/low alpha

前提是你 提交于 2019-12-11 01:39:26

问题


There's a 3x3 image. The CanvasPixelArray is:

[12,24,48,255,12,24,48,255,12,24,48,255,12,24,48,255,12,24,48,255,12,24,48,255,12,24,48,255,12,24,48,255,12,24,48,255]

I change the alpha of all pixels to 0 and back by:

bobs = this.gfx.getImageData(0,0,3,3).data
for (a=3;a<bobs.data.length;a+=4)
bobs.data[a] = 0
this.gfx.putImageData(bobs,0,0)
bobs = this.gfx.getImageData(0,0,3,3).data
for (a=3;a<bobs.data.length;a+=4)
bobs.data[a] = 255
this.gfx.putImageData(bobs,0,0)

All pixels became black. The browser changed the colors to black to save memory. Is there a way to prevent this or should I save a duplicate?


回答1:


I think the reason for this is that Canvas uses premultiplied alpha, meaning all rgb values are multiplied by the alpha value for those pixels. It's done to speed up alpha blending with backgrounds, etc.

There's a section on premultiplied alpha in this article: wikipedia:Alpha_compositing

You'll probably have to either, as you say keep a copy of the unmodified values, or perhaps store an alpha value for the image and set the globalAlpha property before drawing the image. (When I say image, you can equally create a 3x3 canvas, store the pixels there and use drawImage() to draw it to the main canvas).



来源:https://stackoverflow.com/questions/5883220/canvas-putimagedata-color-loss-with-no-low-alpha

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!