在canvas中利用globalCompositeOperation属性可以对同一个画布中的两个图形进行不同的合成效果,这里我运用xor来实现在矩形中挖去一个圆形。
先上图:
实现代码:
var c = document.getElementById("mycanvas");
var ctx = c.getContext('2d');
ctx.fillStyle = "blue";
ctx.fillRect(0, 0, 400, 200);//矩形
ctx.globalCompositeOperation = "xor";//重叠部分会变成透明
ctx.beginPath();
ctx.arc(200, 100, 100, 0, 2*Math.PI);//圆
ctx.fillStyle="blue";
ctx.fill();
之后把需要展示的放在底层就可以实现下图效果,只需要把矩形填充颜色改为白色即可
ctx.fillStyle="white";