Skip to content Skip to sidebar Skip to footer

Circular Crop For Html Canvas

I have a square context and I am trying to 'cut' the canvas into a circle. I've tried using clip() but this only works prior to having things drawn onto the canvas. Is there any wa

Solution 1:

You can use context.globalCompositeOperation='destination-in' to do an "after the fact" clip.

enter image description here

Example code and a Demo:

var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;

var img=newImage();
img.onload=start;
img.src="https://i.stack.imgur.com/oURrw.png";
functionstart(){
  var cw,ch;
  cw=canvas.width=img.width;
  ch=canvas.height=img.height;
  ctx.drawImage(img,0,0);
  ctx.globalCompositeOperation='destination-in';
  ctx.beginPath();
  ctx.arc(cw/2,ch/2,ch/2,0,Math.PI*2);
  ctx.closePath();
  ctx.fill();
}
body{ background-color: ivory; }
canvas{border:1px solid red;}
Original Image:<br><imgsrc='https://i.stack.imgur.com/oURrw.png'><br>
Clip existing content into circle with Compositing<br><canvasid="canvas"width=300height=300></canvas>

Post a Comment for "Circular Crop For Html Canvas"