是否有一个很好的解决方案来绘制带有画布的叠加颜色的位图?
我要做的是为所有不透明的像素绘制一个具有独特颜色的位图。 我没有找到任何解决方案,它对我来说很有用!
感谢的
答案 0 :(得分:2)
<强> Live Demo 强>
一种方法是循环每个像素并将r / g / b值更改为您想要的值。通过跳过alpha值,它只会将不透明像素更改为您想要的颜色。
var canvas = document.getElementById("canvas"),
ctx = canvas.getContext("2d"),
image = document.getElementById("testImage");
ctx.drawImage(image,0,0);
var imgd = ctx.getImageData(0, 0, 128, 128),
pix = imgd.data,
uniqueColor = [0,0,255]; // Blue for an example, can change this value to be anything.
// Loops through all of the pixels and modifies the components.
for (var i = 0, n = pix.length; i <n; i += 4) {
pix[i] = uniqueColor[0]; // Red component
pix[i+1] = uniqueColor[1]; // Green component
pix[i+2] = uniqueColor[2]; // Blue component
//pix[i+3] is the transparency.
}
ctx.putImageData(imgd, 0, 0);
// Just extra if you wanted to display within an img tag.
var savedImageData = document.getElementById("imageData");
savedImageData.src = canvas.toDataURL("image/png");