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
  • 13,296
  • 21
  • 55
  • 51
Valentina
  • 131
  • 1
  • 1
  • 3

5 Answers5

4

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
  • 92,182
  • 29
  • 231
  • 348
Artpanther
  • 41
  • 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,468
  • 3
  • 25
  • 38
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
  • 555
  • 1
  • 5
  • 29
Nitesh
  • 1,205
  • 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,181
  • 1
  • 17
  • 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
  • 58,927
  • 8
  • 76
  • 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