Valentina
Valentina

Reputation: 131

HTML5 Canvas eraser

There's a way of implementing an eraser (other than using a white pencil?).

I'm using layering, I have an image below the canvas, so, if eraser paints white, the user is going to notice since the below image isn't solid white.

Upvotes: 13

Views: 19533

Answers (5)

Artpanther
Artpanther

Reputation: 51

https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial/Compositing

Actually the function is:

function eraser(){
    context.globalCompositeOperation = "destination-out";  
    context.strokeStyle = "rgba(255,255,255,1)";
}

And you can go back to source-over.

Upvotes: 5

Altanai
Altanai

Reputation: 1393

Code for transparent eraser using globalCompositeOperation "destination-out" and "source-over"

var handleMouseMove = function (event) {
    midPt = new createjs.Point(oldPt.x + stage.mouseX>>1, oldPt.y+stage.mouseY>>1);

   if(curTool.type=="eraser"){

      var tempcanvas = document.getElementById('drawcanvas');
      var tempctx=tempcanvas.getContext("2d");
      tempctx.beginPath();
      tempctx.globalCompositeOperation = "destination-out";   
      tempctx.arc(midPt.x, midPt.y, 20, 0, Math.PI * 2, false);     
      tempctx.fill();
      tempctx.closePath();
      tempctx.globalCompositeOperation = "source-over";
      drawingCanvas.graphics.clear();

      // keep updating the array for points 
      arrMidPtx.push(midPt.x);
      arrMidPty.push(midPt.y);
      stage.addChild(drawingCanvas);
      stage.update();

    }

I have used easeljs here however the code is independent from it and can be integrated with any canvas html5 drawing javascript code

Upvotes: 0

Nitesh
Nitesh

Reputation: 1267

function eraser()
{                                
context.strokeStyle = "rgb(255, 255, 255)";
context.globalCompositeOperation = "copy";  
context.strokeStyle = ("rgba(255,255,255,255)"); /* or */ context.fillStyle = "rgba(255,0,0,0)";
}

both worked in my case!

Upvotes: 2

ChessWhiz
ChessWhiz

Reputation: 4702

As an alternative, you can use multiple <canvas> objects drawn over each other, then erase from the top canvas to reveal the image beneath. See: html5 - canvas element - Multiple layers

Upvotes: 2

Javier
Javier

Reputation: 62573

set the pencil color to transparent:

context.fillStyle = "rgba(255,0,0,0)";

in rgba() format, the last one is the alpha channel, 0 is totally transparent

Upvotes: -2

Related Questions