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?
You can use context.globalCompositeOperation='destination-in'
to do an "after the fact" clip.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With