Skip to content Skip to sidebar Skip to footer

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:

enter image description here

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);


function cut(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();
}


function handleMouseDown(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;}
<script src="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>
<img id=bk src='https://dl.dropboxusercontent.com/u/139992952/stackoverflow/KoolAidMan.png'>
<canvas id="canvas" width=300 height=300></canvas>

Post a Comment for "HTML5 Cut Out Circle From Previous Drawn Strokes"