HTML5如何在画布中绘制透明像素图像
问题描述:
我正在使用rgb像素数据绘制图像。我需要为该图像设置透明背景颜色。我可以将alpha设置为透明图像的值是多少?或者还有其他解决方案吗?
I'm drawing an image using rgb pixel data. I need to set transparent background color for that image. What value I can set for alpha to be a transparent image? Or is there any other solution for this?
答
如果我理解你的需要,你基本上想要将图像上的特定颜色变为透明。要做到这一点,你需要使用 getImageData
签出 mdn有关像素操作的解释。
If I understand what you need, you basically want to turn specific colors on an image transparent. To do that you need to use getImageData
check out mdn for an explanation on pixel manipulation.
下面是一些示例代码
var imgd = ctx.getImageData(0, 0, imageWidth, imageHeight),
pix = imgd.data;
for (var i = 0, n = pix.length; i <n; i += 4) {
var r = pix[i],
g = pix[i+1],
b = pix[i+2];
if(g > 150){
// If the green component value is higher than 150
// make the pixel transparent because i+3 is the alpha component
// values 0-255 work, 255 is solid
pix[i + 3] = 0;
}
}
ctx.putImageData(imgd, 0, 0);
And a working demo
使用上面的代码,您可以使用
With the above code you could check for fuschia by using
来检查fuschia if(r == 255&& g == 0&& b == 255)