Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript/jQuery: remove shape/path from canvas

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

beginPath();
bezierCurveTo();
stroke();
closePath();

How can I remove this from the canvas once it's been created? I need to be able to call the remove function via toggle() and blur(). I'm sure something exists for this...

Thanks in advance for any help!

like image 430
bobsoap Avatar asked Apr 03 '10 16:04

bobsoap


People also ask

How do you remove shapes from canvas?

You can't remove a path/shape from the canvas. You can draw something else over it or clear the canvas. Show activity on this post. You might try using SVG instead of canvas.

How do you clear canvas and redraw?

To clear the Canvas, you can use the clearRect() method. This method performs pretty well than others for clearing the canvas (such as resetting the width/height, destroying the canvas element and then recreating it, etc..) const context = canvas. getContext('2d'); context.

How do I reset my canvas?

From the course navigation menu, select Settings. In the "Settings" sidebar at the right, select Delete All Course Content. You will be prompted to confirm. To proceed, click Reset Course Content, or click Cancel to cancel.

How do you erase a picture on canvas?

You can easily clear you canvas by resetting its width and height. For example: canvas. width = canvas. width should clear your drawing context.


2 Answers

Try this:

ctx.save();
ctx.globalCompositeOperation = "destination-out";
// drawing here you path second time
ctx.restore();

"The globalCompositeOperation attribute sets how shapes and images are drawn onto the scratch bitmap" specs

How it works you can see here.

like image 164
agegorin Avatar answered Sep 23 '22 09:09

agegorin


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:

  1. Overlay <canvas> elements into a stack of layers
  2. Use <svg> in which each visual element is distinct from the other elements and may be manipulated independently

You 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.

like image 33
Drew Noakes Avatar answered Sep 23 '22 09:09

Drew Noakes