javascript - 如果不透明,则为 PNG 文件区域着色

标签 javascript html canvas

您是否知道任何好的解决方案(也可以基于 Canvas ),使开发人员能够在非透明区域(如蒙版)更改 png 图像的颜色(用十六进制颜色填充)?我需要会改变颜色(或背景图像)的透明区域,这就是为什么它必须保持不变。

最佳答案

要执行您想要的操作,您需要使用 getImageDataputImageData 查看 mdn for an explanation on pixel manipulation .

下面是一些示例代码

var canvas = document.getElementById("canvas"),
    ctx = canvas.getContext("2d"),
    image = document.getElementById("testImage");

canvas.height = canvas.width = 135;
ctx.drawImage(image,0,0);

var imgd = ctx.getImageData(0, 0, 135, 135),
    pix = imgd.data,
    newColor = {r:0,g:100,b:200};

for (var i = 0, n = pix.length; i <n; i += 4) {
    var r = pix[i],
            g = pix[i+1],
            b = pix[i+2];

        if(r == 216 && g == 6 && b == 6){ 
            // Change the red to whatever.
            pix[i] = newColor.r;
            pix[i+1] = newColor.g;
            pix[i+2] = newColor.b;
        }
}

ctx.putImageData(imgd, 0, 0);​

Example demo

使用上面的代码,您可以使用以下方法检查紫红色

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

然后只需将 newColor 更改为替换颜色即可。

关于javascript - 如果不透明,则为 PNG 文件区域着色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10878477/

相关文章:

php - 如何将值显示到数据库中的字段中

javascript - 无法获取排序项目数组以在屏幕上显示结果?

html - 使用 SandcaSTLes 在 CHM 帮助文件中嵌入图像

javascript - 避免多次加载 javascript 文件

javascript - 在 do while 中,document.write 不起作用(javascript)

javascript - 轻松纺车

HTML5 Canvas : is there a way to resize image with "nearest neighbour" resampling?

javascript - 保存要在以后的动画帧中重绘的 <canvas> 内容?

java - Java 到 NodeJS 的通信?

javascript - 阅读网页上的 Word/.docx 文档