How to wash on canvas without erasing the background

I have a canvas on which drawimage() is the background.

I have an eraser tool with which I want to erase what I am painting, but not the image that I have on canvas. I know that I can put the image as a separate element behind the canvas, but this is not what I want, because I want to save what is on the canvas as an image.

My drawing function is here:

 function draw (event) { if (event == 'mousedown') { context.beginPath(); context.moveTo(xStart, yStart); } else if (event == 'mousemove') { context.lineTo(xEnd, yEnd); } else if (event == 'touchstart') { context.beginPath(); context.moveTo(xStart, yStart); } else if (event == 'touchmove') { context.lineTo(xEnd, yEnd); } context.lineJoin = "round"; context.lineWidth = gadget_canvas.radius; context.stroke(); } 

If I need to explain further, I will.

Thanks in advance.

+4
source share
2 answers

There are several ways to do this.

I would recommend putting the image as a CSS canvas "background-image". Then draw on the canvas as usual.

If you want to save the Canvas as an image, you will need to execute a sequence of events:

  • Create a canvas in memory the size of your regular canvas. Call it can2
  • ctx2.drawImage(can1, 0, 0) // Draw the first canvas on a new canvas
  • ctx.clearRect(0, 0, width, height) // clear the first canvas
  • ctx.drawImage(background, 0, 0) // draw an image on the first canvas
  • ctx.drawImage(can2, 0, 0) // draw the (saved) first canvas back to itself

This will allow you to get the best of both worlds.

+5
source

I saved the image path in the array when I cleaned the canvas. I call the init function again:

 $( ".clear_canvas" ).click(function() { console.log("clear"); var canvas = document.getElementById("canvasMain"), ctx=canvas.getContext("2d"); ctx.setTransform(1, 0, 0, 1, 0, 0); ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height); //load the image again init(path,width,height); }); 
0
source

All Articles