Search code examples
htmlcanvas

"Erasing" in html5 canvas


I have a doodling application in html5 canvas, and I'm trying to figure out the best way to implement an eraser control. First impulse was just to have the eraser draw the background color [white], but this is problematic because if the user moves an image or another layer to where they've previously erased, they see the white drawing where they erased.

Ideally, I'd like to have the erase control change the pixels to black transparent. I can't simply use lineTo to do this because, obviously, it just draws a black transparent line over it, and that leaves the original doodle untouched. Any ideas on how to do this?

Thanks.


Solution

  • If you want to draw a black transparent stroke, you probably want:

    context.globalCompositeOperation = "destination-out";
    context.strokeStyle = "rgba(0,0,0,1)";
    

    Remember to save the previous globalCompositeOperation and then restore it later or transparency won't work properly!