I can\'t seem to find the function to remove a shape or path from the canvas after it has been created.
So I\'m creating a bezier curve between 2 points with
<
As far as I remember the specification you must call context.save() before drawing, then draw something, and then call context.restore() to return to the previous state.
To clear your canvas, use the following code
canvas_context.clearRect(0,0,canvas_1.width,canvas_1.height);
Always use beginPath method when you are starting to draw a new path and closePath method after you finished drawing your path.
NOTE: Paths that are not closed cannot be cleared.
If your paths are not getting cleared, it must be because of the above reason.
All path MUST begin with beginPath() and end with closePath()
Example:
canvas_context.beginPath();
canvas_context.moveTo(x1,y1);
canvas_context.lineTo(x2,y2);
canvas_context.stroke();
canvas_context.closePath();
The following code also clears your canvas
canvas_1.width = canvas_1.width;
NOTE: The above statement reinitializes a canvas hence it clears a canvas. Any statement that reinitializes a canvas will clear a canvas.
If you're using JQuery:
var elem = $("selector");
var canvas = elem.get(0);
var context = canvas.getContext("2d");
context.clearRect(0, 0, canvas.width, canvas.height);
context.beginPath();
Replace "selector" with your actual JQuery selector.
You might try using SVG instead of canvas. There's a fantastic library called Raphaël that makes working with SVG a breeze. It works in all browsers too, including IE6.
With SVG each shape is its own element that can be moved, transformed, or removed.
This is an important thing to realise about <canvas>
. It's a flattened image made up of pixels. Once something's drawn to it, it's merged into the pixel grid and cannot be differentiated from the other pixels.
If you need to be able to separate image elements you could:
<canvas>
elements into a stack of layers<svg>
in which each visual element is distinct from the other elements and may be manipulated independentlyYou can think of <canvas>
as being a single layer in PhotoShop/Gimp/Fireworks, or an MSPaint document.
You can think of <svg>
as a document in Illustrator/InkScape.
Thanks for the great input to all of you - it helped me find the solution:
context.clearRect(x,y,w,h);
(link)
This will clear anything within that rectangle.
I found the method on the page I found while digging for ILog's answer to save/restore the context, and it's all on there. Thanks again.