簡體   English   中英

html5 canvas - 如何使用“目標輸出”僅清除最近繪制的形狀?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM