Html5 Cut Out Circle From Previous Drawn Strokes
How can you cut out a circle on a previous drawn canvas in html5? I tried filling it transparent, and of course it did not work, I can fill it with a color but I really need it to
Solution 1:
You can use compositing to do a 'reveal' of an image underneath the canvas.
- Position a canvas directly over an image using CSS positioning.
- Fill the top canvas with a solid color.
- Listen for mousedown events.
- In the event handler, set compositing to 'destination-out' which will use any new drawings to "cut" out any existing pixels.
- Draw on the canvas (causing the img underneath to be revealed where the new drawings were drawn.
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var $canvas=$("#canvas");
var canvasOffset=$canvas.offset();
var offsetX=canvasOffset.left;
var offsetY=canvasOffset.top;
var radius=30;
ctx.fillStyle='skyblue';
ctx.fillRect(0,0,canvas.width,canvas.height);
functioncut(x,y,radius){
ctx.save();
ctx.globalCompositeOperation='destination-out';
ctx.beginPath();
ctx.arc(x,y,radius, 0, 2 * Math.PI, false);
ctx.fill();
ctx.restore();
}
functionhandleMouseDown(e){
e.preventDefault();
e.stopPropagation();
x=parseInt(e.clientX-offsetX);
y=parseInt(e.clientY-offsetY);
cut(x,y,radius);
}
$("#canvas").mousedown(function(e){handleMouseDown(e);});
body{ background-color: ivory; }
#canvas{border:1px solid red;}
#wrapper{position:relative;}
#bk,#canvas{position:absolute;}
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script><h4>Click on the canvas to cut a circle<br>and reveal the img underneath.</h4><imgid=bksrc='https://dl.dropboxusercontent.com/u/139992952/stackoverflow/KoolAidMan.png'><canvasid="canvas"width=300height=300></canvas>
Post a Comment for "Html5 Cut Out Circle From Previous Drawn Strokes"