【问题标题】:How to make only two shapes compost together in HTML canvas without effecting other shapes如何在 HTML 画布中仅使两个形状一起堆肥而不影响其他形状
【发布时间】:2021-12-23 10:12:27
【问题描述】:

所以我的目标很简单……我想。我想画一个中间有一个洞的矩形。但我不希望那个洞穿过画布上的任何其他东西。 现在我有这样的东西:

context.fillStyle = 'blue';
    context.fillRect(0, 0, width, height);

    context.fillStyle = "#000000";
    context.beginPath();
    context.rect(0, 0 , width, height);
    context.fill();
    enter code here

    context.globalCompositeOperation="destination-out";

    context.beginPath();
    context.arc(width / 2, height / 2 , 80, 0, 50);
    context.fill();

但这也切穿了背景,我怎样才能让它只切穿黑色矩形而没有别的呢?

视觉示例,以防我解释得不好:

【问题讨论】:

    标签: javascript html5-canvas


    【解决方案1】:

    看看这是否是你要找的:

    <canvas id="canvas" width="200" height="160"></canvas>
    
    <script>
      class Shape {
        constructor(x, y, width, height, color) {
          this.color = color
          this.path = new Path2D();
          this.path.arc(x, y, height / 3, 0, 2 * Math.PI);
          this.path.rect(x + width / 2, y - height / 2, -width, height);
        }
    
        draw(ctx) {
          ctx.beginPath();
          ctx.fillStyle = this.color;
          ctx.fill(this.path);
        }
      }
    
      var canvas = document.getElementById("canvas");
      var ctx = canvas.getContext("2d");
    
      shapes = [];
      shapes.push(new Shape(40, 40, 80, 80, "blue"));
      shapes.push(new Shape(60, 65, 70, 70, "red"));
      shapes.push(new Shape(80, 40, 65, 65, "gray"));
    
      shapes.forEach((s) => {
        s.draw(ctx);
      });
    </script>

    我使用Path2D() 是因为我有一个我之前做过的快速示例,但没有它也应该是可行的。背后的理论很简单,我们只是想在圆圈上填充对面。

    我将半径硬编码为高度的三分之一,但您可以将所有这些更改为其他内容,甚至是最终用户可以更改的参数

    【讨论】:

    • 这个!!谢谢!!
    【解决方案2】:

    这是您希望实现的目标吗?

    const context = document.getElementById("canvas").getContext('2d');
    const width = 100;
    const height = 100;
    const circleSize = 30;
    
    context.fillStyle = "black";
    context.fillRect(0, 0 , width, height);
    
    context.beginPath();
    context.arc(width / 2, height / 2, circleSize, 0, 2 * Math.PI);
    context.clip();
    
    context.fillStyle = "blue";
    context.fillRect(0, 0, width, height);
    &lt;canvas id="canvas"/&gt;

    这篇文章可能有用:
    https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial/Compositing

    在上面的示例中,我使用的是clip。 正如文档所述:

    Canvas 2D API 的 CanvasRenderingContext2D.clip() 方法将当前或给定路径转换为当前剪辑区域。

    这意味着在此行之后添加到上下文中的任何元素都只会在该剪切路径内绘制。

    【讨论】:

    • 从问题中的示例图像中,圆圈应该是透明的而不是蓝色
    • @HelderSepulveda 我理解这个问题,右边的图像是目标。而左边的图像是解释应该应用这些层的一种方式。这是由“但这也穿过背景,我如何让它只穿过黑色矩形而没有别的?”这一行强制执行的。
    • 查看我的答案,了解如何绘制一个中间有一个洞的矩形,这就是我们绘制的方式,而不是实际切出一些东西
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-02-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多