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
Solution 1:
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.
Solution 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
Solution 3:
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!
Solution 4:
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
Solution 5:
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
Post a Comment for "Html5 Canvas Eraser"