2011-08-28 70 views
0

是否有一个很好的解决方案来绘制带有画布叠加颜色的位图?Html5 Canvas overlay

我正在做的是绘制一个独特的颜色为所有不透明像素的位图。 我没有找到任何解决方案,它可能对我有用!

感谢的

+0

我以前没有这样做,但我认为XOR操作可以做到这一点(10年前,XOR和Java小程序做到了这一点).. http://www.whatwg.org/specs/web-apps /current-work/multipage/the-canvas-element.html搜索XOR –

回答

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"); 
+0

yeap。我尝试了这种方法,但对于我的需求来说太小了。 – webshaker

+0

@webshaker你的意思是太小?以上仅使用示例图像。 – Loktar

+0

oups太慢抱歉。实际上我会解释我要做的事情。我正在编辑。我希望能够在屏幕中选择一个精灵。我使用精灵的方形区域进行了检测,但它不够准确。我喜欢用特定的颜色将每个精灵绘制到一个隐藏的缓冲区中,以便找到所选精确的精灵。 – webshaker