html画布的循环裁剪

时间:2014-10-13 22:27:25

标签: html5 canvas html5-canvas

我有一个正方形的背景,我正在尝试" cut"画布变成圆圈。我尝试过使用clip(),但这只能在将东西绘制到画布上之前使用。有什么方法可以在绘制完所有画布后裁剪画布吗?

1 个答案:

答案 0 :(得分:4)

您可以使用context.globalCompositeOperation='destination-in'在“事后”剪辑后执行“。”

enter image description here

示例代码和演示:

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>