How can I combine alpha with compositing in Images?

无人久伴 提交于 2019-12-11 04:22:05

问题


I have an HTML5 Canvas. I am using the KineticJS(KonvaJS) canvas library. The canvas contains an Image as shown below. Now I want to erase pixels but being combined with a certain transparency level. The red dot erases the pixels with transparency 0. This was solved in this question. The green dot erases the pixel with transparency level of 0.5. The higher the transparency the smaller is the effect of the eraser.

How can I define the strength of the eraser?


回答1:


You can use 'destination-out` compositing to "erase" pixels on a canvas. By default, the erasure will be completely through to the background.

ctx.drawImage(img,0,0);
ctx.globalCompositeOperation='destination-out';
ctx.fillRect(100,50,50,50);

But you can also control how much alpha is erased by setting the globalAlpha to less than 1.00. This causes the erasure to reduce the alpha of the existing pixels--similar to color blending.

ctx.drawImage(img,0,0);
ctx.globalCompositeOperation='destination-out';
ctx.globalAlpha=0.50;
ctx.fillRect(200,50,50,50);



回答2:


// Get the canvas pixel array.
var img = context.getImageData(x, y, w, h);

// then loop through the array 
// modifying each pixel one by one as you need
for (var i = 0, l = img.data.length; i < l; i += 4) {
    img.data[i  ] = ...; // red
    img.data[i+1] = ...; // green
    img.data[i+2] = ...; // blue
    img.data[i+3] = ...; // alpha
}

// put back the data in canvas
context.putImageData(img, x, y);

The strength of the erasor would probably be set via the alpha channel. Hope that gets you started.



来源:https://stackoverflow.com/questions/28441093/how-can-i-combine-alpha-with-compositing-in-images

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