我有一个方形背景,我想“切”画布成一个圆圈。 我用夹子()尝试,但仅此之前,有画在画布上的东西的作品。 有没有什么办法来裁剪画布一切都已经画上它之后?
Answer 1:
您可以使用context.globalCompositeOperation='destination-in'
做一个“事后”的剪辑。
示例代码和一个演示:
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>
文章来源: Circular crop for html canvas