Html5 Canvas overlay

ぐ巨炮叔叔 提交于 2019-12-30 07:48:08

问题


Is there a good solution to draw a bitmap with an overlay color with canvas ?

What I'm looking to do is drawing a bitmap with a unique color for all not transparent pixel. I do not find any solution for that, and it could be usefull for me !

Thank's


回答1:


Live Demo

One way to do it is to loop through each pixel and change the r/g/b values to the value you want it. By skipping over the alpha value it will only change the opaque pixels to the color you want.

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


来源:https://stackoverflow.com/questions/7221816/html5-canvas-overlay

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!