1

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.

enter image description here

How can I define the strength of the eraser?

Community
  • 1
  • 1
Michael
  • 32,527
  • 49
  • 210
  • 370

2 Answers2

2

enter image description here

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);
markE
  • 102,905
  • 11
  • 164
  • 176
  • Is globalAlpha aplied I the current pixel of the image or to the newly drawn squares in your case? Is it possible to vary the alpha of each eraser or is it always the same? – Michael Feb 10 '15 at 21:53
  • 1
    Nice thing is you can vary globalAlpha whenever you want to! Prior erasures are not afftected and any future erasures will be done at your new globalAlpha. If you erase over a previously erased area, the erasure will be the sum of the previous alpha erasure(s) and the new alpha erasure. Good luck with your project! – markE Feb 10 '15 at 22:13
  • Could you please help me with this issue? http://stackoverflow.com/questions/28638627/draw-smooth-lines-on-a-canvas – Michael Feb 20 '15 at 21:35
0
// 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.

mika
  • 1,411
  • 1
  • 12
  • 23