【问题标题】:transparent circle on opaque canvas不透明画布上的透明圆圈
【发布时间】:2022-01-26 20:49:17
【问题描述】:

我正在尝试在 HTML 画布上绘制一个透明的圆圈。代码如下:


    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 演示。

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

【问题讨论】:

    标签: javascript html5-canvas


    【解决方案1】:

    您正在使用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>

    【讨论】:

    • @JPM 我想念了解 globalCompositeOperation 的工作原理。感谢您消除我的疑问。
    猜你喜欢
    • 2020-09-15
    • 2013-11-25
    • 2014-01-02
    • 2012-02-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多