Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 way to crop a canvas after everything has been drawn on it?

like image 600
Siva Avatar asked Oct 13 '14 22:10

Siva


Video Answer


1 Answers

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=new Image();
img.onload=start;
img.src="https://i.stack.imgur.com/oURrw.png";
function start(){
  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>
<img src='https://i.stack.imgur.com/oURrw.png'><br>
Clip existing content into circle with Compositing<br>
<canvas id="canvas" width=300 height=300></canvas>
like image 125
markE Avatar answered Oct 06 '22 08:10

markE