3

How can I use globalCompositeOperation for erasing something?

http://canvaspaint.org/ has an eraser, but that's just a white line - ok only if your background is white...

I know you can use ctx.clearRect(). But it didn't really worked for me because while dragging a mouse with eraser (set to 8x8px) it only makes unconnected 8x8px squares - not really a smooth line.

Is there a way how to use globalCompositeOperation as an eraser?

Something like:

ctx.globalCompositeOperation = "___something___";
ctx.beginPath();
ctx.lineTo(mouseX , mouseY);
ctx.closePath();

Thank you.

jack moore
  • 1,989
  • 4
  • 25
  • 22

3 Answers3

6

Yes you can erase using globalCompositeOperation as described here. Just set it to "copy" and use e.g. strokeStyle = "rgba(0,0,0,0)" and that will clear the canvas in the stroke.

Update: thanks for pointing out this doesn't work now @will-huang. You should as mentioned have globalCompositeOperation set to destination-out and strokeStyle set to rgba(0,0,0,1). (Actually you can have any RGB values, just you need the alpha set to 1.0 to fully erase the contents of the stroke.)

Here's an example of erasing: http://jsfiddle.net/FGcrq/1/

Community
  • 1
  • 1
andrewmu
  • 14,276
  • 4
  • 39
  • 37
  • 1
    assign globalCompositeOperation to "copy" unable to run correctly in IE9/IE10. I was changed to "destination-out" and change strokeStyle to "rgba(0,0,0,1)" to solve this problem. – Will Huang Sep 11 '12 at 16:02
2
ctx.globalCompositeOperation = "destination-out";

That should do the trick. You can also use "xor" for erasing goodness.

Michael Deal
  • 2,948
  • 2
  • 18
  • 8
  • I agree. context.strokeStyle = "rgba(255,255,255,0.7)"; context.globalCompositeOperation = "destination-out" is better than "copy" because you can adjust eraser to different strengths. – Homan Apr 11 '12 at 18:49
0

I don't think so. But just change the line color to whatever the background color is. Also, if you want different sizes of eraser increase the line size. ctx.lineWidth=//default 1.0 and ctx.strokeStyle=//default black I would also suggest using ctx.save() and ctx.restore() so you don't have to worry about resetting your line attributes.

qw3n
  • 6,236
  • 6
  • 33
  • 62