[英]How to erase a stroke in canvas with globalCompositeOperation = 'destination-out'?
[英]html5 canvas - how to use 'destination-out' to clear out the most recently drawn shape only?
假設我畫了一個綠色矩形,然后在它上面畫了一個藍色矩形。 我想在藍色矩形中畫一個圓孔,以便通過孔可以看到下面的綠色矩形。
我試過使用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>
創建第二個 canvas,將藍色矩形添加到其中,切出圓形,然后將其合並到第一個 canvas 中:
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>
要在當前內容后面繪制,請使用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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.