13

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.

JasonMArcher
  • 14,195
  • 22
  • 56
  • 52
Valentina
  • 131
  • 1
  • 1
  • 3

5 Answers5

5

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.

gman
  • 100,619
  • 31
  • 269
  • 393
Artpanther
  • 51
  • 1
  • 1
2

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

Community
  • 1
  • 1
ChessWhiz
  • 4,656
  • 3
  • 26
  • 40
2
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!

Fabián
  • 565
  • 1
  • 7
  • 30
Nitesh
  • 1,241
  • 4
  • 16
  • 25
0

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

Altanai
  • 1,323
  • 1
  • 19
  • 33
-2

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

Javier
  • 60,510
  • 8
  • 78
  • 126
  • 1
    It does't work. The 'eraser pencil' stills draw on red (the color of the actual drawing pencil). – Valentina Sep 24 '10 at 19:38
  • try setting the color as simply "transparent" (http://dev.w3.org/csswg/css3-color/#transparent), or maybe `strokestyle` instead of `fillstyle` – Javier Sep 24 '10 at 19:43
  • =( Nothing. I already tried both context.strokeStyle = "rgba(0,0,0,0)"; and context.fillStyle = "rgba(0,0,0,0)";. Any ideas? – Valentina Sep 24 '10 at 19:46