【问题标题】:html5 canvas - how to use 'destination-out' to clear out the most recently drawn shape only?html5 canvas - 如何使用“destination-out”仅清除最近绘制的形状?
【发布时间】:2021-10-23 09:48:28
【问题描述】:
假设我画了一个绿色矩形,然后在它上面画了一个蓝色矩形。我想在蓝色矩形上画一个圆形孔,这样下面的绿色矩形就可以通过孔看到。
我尝试过使用destination-out,但它会清除下面的所有形状:
const ctx = document.querySelector("#canvas").getContext("2d");
ctx.fillStyle = "green";
ctx.fillRect(0, 0, 50, 100);
ctx.fillStyle = "blue";
ctx.fillRect(0, 0, 50, 50);
ctx.globalCompositeOperation = "destination-out";
ctx.beginPath();
ctx.arc(50 / 2 - 10 / 2, 50 / 2, 10, 0, Math.PI * 2);
ctx.fill();
ctx.globalCompositeOperation = "source-over";
<canvas
id="canvas"
width="500"
height="200"
style="background: black"
></canvas>
【问题讨论】:
标签:
javascript
html
canvas
html5-canvas
【解决方案1】:
要在当前内容后面绘制,请使用destination-over 复合模式:
const ctx = document.querySelector("#canvas").getContext("2d");
ctx.fillStyle = "blue";
ctx.fillRect(0, 0, 50, 50);
ctx.globalCompositeOperation = "destination-out";
ctx.beginPath();
ctx.arc(50 / 2 - 10 / 2, 50 / 2, 10, 0, Math.PI * 2);
ctx.fill();
ctx.globalCompositeOperation = "destination-over";
ctx.fillStyle = "green";
ctx.fillRect(0, 0, 50, 100);
<canvas
id="canvas"
width="500"
height="200"
style="background: black"
></canvas>
【解决方案2】:
创建第二个画布,将蓝色矩形添加到其中,剪下圆形,然后将其合并到第一个画布中:
const ctx = document.querySelector("#canvas").getContext("2d");
ctx.fillStyle = "green";
ctx.fillRect(0, 0, 50, 100);
const canvasTemp = document.createElement("canvas");
const ctxTemp = canvasTemp.getContext("2d");
ctxTemp.fillStyle = "blue";
ctxTemp.fillRect(0, 0, 50, 50);
ctxTemp.globalCompositeOperation = "destination-out";
ctxTemp.beginPath();
ctxTemp.arc(50 / 2 - 10 / 2, 50 / 2, 10, 0, Math.PI * 2);
ctxTemp.fill();
ctxTemp.globalCompositeOperation = "source-over";
ctx.drawImage(canvasTemp, 0, 0);
<canvas
id="canvas"
width="500"
height="200"
style="background: black"
></canvas>