【问题标题】:How can I clip INSIDE union of multiple shapes in HTML5 canvas?如何在 HTML5 画布中剪辑多个形状的 INSIDE union?
【发布时间】:2020-12-14 09:08:02
【问题描述】:

我想剪裁给定路径的一些圆形或矩形孔。 CanvasRenderingContext2D.clearRect() 在这里不起作用,因为我需要显示背景。 我在这里引用了答案: https://stackoverflow.com/a/18993901/3066086

但触摸形状时它不起作用。 这是演示我的应用程序的代码和结果/所需结果的图片:

<canvas id="canvas" width = "500" height="500" ></canvas>
<script>
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');

ctx.rect(0, 0,500, 500);
ctx.fillStyle = 'rgba(100,100,100,1)';
ctx.fill();

ctx.beginPath();
ctx.rect(0,0,500,500);
ctx.arc(100, 250, 50, 0, 2 * Math.PI);
ctx.closePath();
ctx.arc(300, 250, 50, 0, 2 * Math.PI);
ctx.closePath();
ctx.rect(95,245,200,10);
ctx.clip('evenodd');
ctx.beginPath();
ctx.rect(5, 5, 400, 400);
ctx.fillStyle = 'rgba(255,0,0,1)';
ctx.fill();
</script>

结果:

想要的结果:

【问题讨论】:

    标签: html5-canvas clipping


    【解决方案1】:

    使用globalCompositeOperation

    您可以使用它来剪切图像ctx.globalCompositeOperation = "destination-out";的部分内容

    并且只绘制图像的透明部分。 ctx.globalCompositeOperation = "destination-over"

    因此,与其先绘制背景,不如先绘制外部形状,然后剪下需要的部分,最后在所有内容后面绘制背景。

    示例

    const ctx = canvas.getContext('2d');
    
    // draw red box first
    ctx.beginPath();
    ctx.rect(5, 5, 400, 400)
    ctx.fillStyle = "#F00";
    ctx.fill();
    
    // Cut out circles using globalCompositeOperation  "destination-out"
    ctx.globalCompositeOperation = "destination-out";
    ctx.fillStyle = "#000";
    ctx.beginPath();
    ctx.arc(100, 250, 50, 0, 2 * Math.PI);
    ctx.closePath();
    ctx.arc(300, 250, 50, 0, 2 * Math.PI);
    ctx.closePath();
    ctx.rect(95,245,200,10);
    ctx.fill();
    
    // Add background last using "destination-over";
    ctx.globalCompositeOperation = "destination-over";
    ctx.rect(0, 0,500, 500);
    ctx.fillStyle = "#999";
    ctx.fill();
    &lt;canvas id="canvas" width = "500" height="500" style="width:200px;height:200px;"&gt;&lt;/canvas&gt;

    【讨论】:

      猜你喜欢
      • 2013-09-30
      • 2014-10-06
      • 2015-10-12
      • 2023-03-03
      • 2018-10-14
      • 1970-01-01
      • 1970-01-01
      • 2012-08-14
      • 1970-01-01
      相关资源
      最近更新 更多