我正在嘗試在 HTML Canvas 上繪制一個透明的圓圈。這是代碼:
const canvas = document.querySelector('#canvas');
let ctx = canvas.getContext('2d');
canvas.width = 700;
canvas.height = 700;
ctx.beginPath();
ctx.fillStyle = 'rgba(0, 0, 0, 0.5)';
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.globalCompositeOperation = 'destination-out';
ctx.clearRect(50, 50, 200, 200);
ctx.beginPath();
ctx.fillRect(50, 50, 200, 200);
ctx.moveTo(350, 150);
ctx.beginPath();
ctx.arc(350, 150, 80, 0, 2 * Math.PI, false);
ctx.closePath();
ctx.fill();
我能夠使用globalCompositeOperationset to 使矩形透明,destination-out但無法使圓形完全透明。這是MDN關于destination-out操作的說明,
The existing content is kept where it doesn't overlap the new shape.
圓圈仍然應用了一些不透明的顏色。如何讓它完全透明?這是現場演示。
無法理解代碼有什么問題。任何幫助,將不勝感激。
uj5u.com熱心網友回復:
您使用了太多beginpath方法,但這不是問題。
全透明矩形由創建clearRect和未由所述fillRect方法。
所以你應該設定fillStyle為白色,然后代碼作業。
const canvas = document.querySelector('#canvas');
let ctx = canvas.getContext('2d');
canvas.width = 700;
canvas.height = 700;
ctx.beginPath();
ctx.fillStyle = 'rgba(0, 0, 0, .5)';
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = 'rgba(255, 255, 255, 1)';
ctx.globalCompositeOperation = 'destination-out';
ctx.fillRect(50, 50, 200, 200);
ctx.moveTo(350, 150);
ctx.arc(350, 150, 80, 0, 2 * Math.PI, false);
ctx.fill();
ctx.closePath();
body {
background-color: skyblue;
position: relative;
}
img, #canvas {
position: absolute;
}
<body>
<img src="https://images.unsplash.com/photo-1635315850978-44cd0b237006?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=1770&q=80" alt="">
<canvas id="canvas"></canvas>
</body>
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/395437.html
