HTML5如何在画布中绘制透明像素图像 [英] HTML5 how to draw transparent pixel image in canvas

查看:135
本文介绍了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)

这篇关于HTML5如何在画布中绘制透明像素图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆