不透明 canvas 上的透明圆圈

transparent circle on opaque canvas

我正在尝试在 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();

我可以将 globalCompositeOperation 设置为 destination-out 使矩形透明,但无法使圆完全透明。 这是MDN关于destination-out操作的说法,

The existing content is kept where it doesn't overlap the new shape.

圆圈仍然应用了一些不透明的颜色。如何让它完全透明? 这是 live 演示。

无法理解代码有什么问题。任何帮助将不胜感激。

您正在使用 beginpath 方法,但您使用的指令不是路径。

完全透明的矩形是由clearRect创建的,不是是由fillRect方法创建的。

因此您应该将 fillStyle 设置为白色,然后代码才能正常工作。

const canvas = document.querySelector('#canvas');
let ctx = canvas.getContext('2d');

canvas.width = 600;
canvas.height = 400;
    ctx.fillStyle = 'rgba(0, 0, 0, .5)';
    ctx.fillRect(0, 0, canvas.width, canvas.height);
    ctx.globalCompositeOperation = 'destination-out';
    ctx.fillStyle = 'rgba(255, 255, 255, 1)';
    ctx.fillRect(25, 25, 150, 150);
    ctx.arc(275, 100, 60, 0, 2 * Math.PI, false);
    ctx.fill();
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="" width=600 height=390>
  <canvas id="canvas"></canvas>
</body>