Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to erase on canvas without erasing background

I have a canvas to which I drawimage() to be a background.

I have an eraser tool with which I want to be able to erase what I draw but not the image I have in the canvas. I know can place the image as a separate element behind the canvas but that is not what I am after since I desire to save what is in the canvas as a 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.

Thank you in advance.

like image 731
ryuutatsuo Avatar asked Aug 01 '11 03:08

ryuutatsuo


1 Answers

There are a few ways you can go about this.

I'd recommend putting the image as the canvas's CSS "background-image". Then draw on the canvas as normal.

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

  1. Create an in-memory canvas just as big as your normal canvas. Call it can2
  2. ctx2.drawImage(can1, 0, 0) // paint first canvas onto new canvas
  3. ctx.clearRect(0, 0, width, height) // clear first canvas
  4. ctx.drawImage(background, 0, 0) // draw image on first canvas
  5. ctx.drawImage(can2, 0, 0) // draw the (saved) first canvas back to itself

This will let you have the best of both worlds.

like image 145
Simon Sarris Avatar answered Oct 21 '22 08:10

Simon Sarris