I’m having trouble implementing an “erase” feature for the objects I draw. I draw objects like so:
function draw_obj1(context) {
context.lineTo(...)
context.arc(...)
//etc
}
And these are drawn overtop of an image background I have for the canvas (via context.createPattern, fillStyle = pattern, etc).
So say the above function traces out a triangle using various lineTo calls. Now to “erase”, or “undo” this drawing, one plan I had was to re-draw the ‘xor’ version of the same object on top of it, to undo it. I do this via context.globalCompositeOperation (see: https://developer.mozilla.org/samples/canvas-tutorial/6_1_canvas_composite.html).
This almost works, except the final result comes up not completely blank against my light-blue background. It comes out as a light-greyish triangle, versus the original black-lined triangle.
EDIT – forgot to mention another idea I tried. Doing ‘clearRect’ on the area I need gone makes a white hole in my light-blue background which is no good.
So how should I go about undoing lines/arcs that I’ve drawn?
Cheers
This won’t be possible using only your Canvas content.
Canvas element reacts like a real canvas: since things are drawn, they are merged and bound to the full picture.
This is because canvas, in most graphic APIs, is just an array of bytes.
Computer can’t know, alone, how to identify and differ the objects composing the current frame.
The best way to do this is to implement something like a “scene graph”, a graph tree.
You could then append objects to this graph tree and construct your own algorythm for drawing each object on the canvas.
You could have a history data structure to allow undo/redo appending/removing objects from the scene graph and redrawing each object in a small timeslice (nano-milliseconds).
That’s a holistic view over your problem. Hope you know how to handle graphs programmatically.
More on here: How to add undo-functionality to HTML5 Canvas?
and here: http://www.abidibo.net/blog/2011/10/12/development-undo-and-redo-functionality-canvas/