"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 leav开发者_Python百科es the original doodle untouched. Any ideas on how to do this?
Thanks.
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!
Note that firefox 3.6/4.0 implement 'copy' by erasing the entire background first. The w3c docs aren't clear as to what should happen here. Chrome (webkit?) interprets the specs as 'only where pixels are actually drawn', for example the result of a stroke().
destination-out with "rgba(255,255,255,1.0)", sets background to transparent where pixels in the framebuffer are not transparent. leaving transparent background in both chrome and firefox.
copy the following page locally, and play with various colors/opacities for the blue box and red circle, and don't forget to make the background color of the page non-white! and
https://developer.mozilla.org/samples/canvas-tutorial/6_1_canvas_composite.html
You'll find browsers are wildly different.
Look into clearRect if your eraser is a rectangle. The clearRect function, as per the specification, will make pixels in the rectangle transparent black, as you want.
If you wish to have other eraser shapes [ie: circle?] you must manipulate pixel data. Note that if you want a feathering-like eraser, this becomes hellish.
Most helpful reference in the world: http://www.whatwg.org/specs/web-apps/current-work/multipage/the-canvas-element.html#the-canvas-element
精彩评论