简体   繁体   English

HTML5 如何在canvas中绘制透明像素图像

[英]HTML5 how to draw transparent pixel image in canvas

I'm drawing an image using rgb pixel data.我正在使用 rgb 像素数据绘制图像。 I need to set transparent background color for that image.我需要为该图像设置透明背景色。 What value I can set for alpha to be a transparent image?我可以为 alpha 设置什么值才能成为透明图像? Or is there any other solution for this?或者还有其他解决方案吗?

If I understand what you need, you basically want to turn specific colors on an image transparent.如果我明白你需要什么,你基本上想把图像上的特定 colors 变成透明的。 To do that you need to use getImageData check out mdn for an explanation on pixel manipulation .为此,您需要使用getImageData查看mdn 以获取有关像素操作的解释

Heres some sample code这是一些示例代码

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使用上面的代码,您可以使用

if(r == 255 && g == 0 && b == 255)

I think you want the clearRect canvas method:我想你想要clearRect canvas 方法:

http://www.w3schools.com/html5/canvas_clearrect.asp http://www.w3schools.com/html5/canvas_clearrect.asp

This will let you clear pixels to transparent (or any other RGBA color) without fuss or pixel manipulation.这将使您无需大惊小怪或像素操作即可将像素清除为透明(或任何其他 RGBA 颜色)。

an alpha of 0 indications that pixel is completely transparent an alpha value of 255 is completely opaque meaning that it will have no transparency. alpha 为 0 表示像素是完全透明的 alpha 值为 255 是完全不透明的,这意味着它没有透明度。

if you portions of your image are completely transparent (an alpha of 0) it doesn't matter what you use for the RGB values as long as use an Alpha of 0. On a side note some older windows programs that I have used make an assumption like the upper left pixel or the lower right pixel is to be used as the transparency color.如果你的图像部分是完全透明的(alpha 为 0),那么只要使用 0 的 Alpha 值,你使用什么 RGB 值并不重要。顺便说一句,我使用过的一些较旧的 windows 程序使假设像左上像素或右下像素将被用作透明颜色。 It would then loop through all of the pixels and set the alpha to 0 when it encountered this specific RGB value.然后它将遍历所有像素并在遇到此特定 RGB 值时将 alpha 设置为 0。

If you use an Alpha of 127 and the image appeared on top of another image it would look like the two images are equally visible or that the bottom image is bleeding 50% of it's colors through to the top image.如果您使用 127 的 Alpha 并且该图像出现在另一幅图像的顶部,则看起来这两幅图像同样可见,或者底部图像将其 colors 的 50% 渗透到顶部图像。

Set a variable for alpha if you want to test and see what it looks like when you apply it to the entire image.如果您想测试并查看将其应用于整个图像时的外观,请为 alpha 设置一个变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM