【问题标题】:canvas path connects when I'm closing them using the new path () [duplicate]当我使用新路径()关闭它们时,画布路径连接[重复]
【发布时间】:2021-03-03 08:24:05
【问题描述】:

我正在使用new Path2D () 创建路径并将它们设置在对象上以便稍后使用isPathInPoint() 检查。

我正在尝试围绕一个框创建 4 个圆圈,但这些圆圈与每次绘制都连接在一起。我知道我每次都可以创建一条新路径,然后将它们推送到一个数组中,但我想知道是否可以只使用一条路径并在不连接的情况下创建它们?

这是一个简单的例子:

            this.hoverPath = new Path2D();
            ctx.beginPath();
            ctx.fillStyle = solidColor;
            this.hoverPath.arc(this.x + this.width, this.y + (this.height / 2), size, 0, 2 * Math.PI);

            ctx.beginPath();
            ctx.fillStyle = solidColor;
            this.hoverPath.arc(this.x + (this.width /2), this.y + this.height, size, 0, 2 * Math.PI);

            ctx.fill(this.hoverPath);

这将创建两个圆圈,但会有一条线将它们连接起来。

如果我创建另外两个,它将在它们之间创建一个连接的框。如何在不将它们推入数组然后创建新路径的情况下实现这一点,或者这就是必须要做的事情?

【问题讨论】:

    标签: javascript canvas


    【解决方案1】:

    看起来你在添加圈子之前忘记移动了...

    请参阅下面的示例,前四个没有移动,我们遇到了您描述的相同问题:

    在我使用移动的第二个,它看起来不错:

    const canvas = document.getElementById('canvas');
    const ctx = canvas.getContext('2d');
    ctx.strokeStyle = "red";
    var size = 15
    
    var pos = {x: 45, y: 45}
    var hoverPath = new Path2D();
    hoverPath.arc(pos.x - 25, pos.y, size, 0, 2 * Math.PI);
    hoverPath.arc(pos.x, pos.y - 25, size, 0, 2 * Math.PI);
    hoverPath.arc(pos.x + 25, pos.y, size, 0, 2 * Math.PI);
    hoverPath.arc(pos.x, pos.y + 25, size, 0, 2 * Math.PI);
    ctx.fill(hoverPath);
    ctx.stroke(hoverPath);
    
    pos = {x: 160, y: 45}
    hoverPath = new Path2D();
    hoverPath.moveTo(pos.x - 25 + size, pos.y);
    hoverPath.arc(pos.x - 25, pos.y, size, 0, 2 * Math.PI);
    hoverPath.moveTo(pos.x + size, pos.y - 25);
    hoverPath.arc(pos.x, pos.y - 25, size, 0, 2 * Math.PI);
    hoverPath.moveTo(pos.x + 25 + size, pos.y);
    hoverPath.arc(pos.x + 25, pos.y, size, 0, 2 * Math.PI);
    hoverPath.moveTo(pos.x + size, pos.y + 25);
    hoverPath.arc(pos.x, pos.y + 25, size, 0, 2 * Math.PI);
    ctx.fill(hoverPath);
    ctx.stroke(hoverPath);
    <canvas id="canvas" width="240" height="90"></canvas>

    【讨论】:

    • 不要移动到中心,你正在追踪一条半径大小的线。而是直接移动到圆弧中的入口点,如下所示:stackoverflow.com/a/31737509/3702797
    • @Kaiido 很好的建议和简单的+ radius
    猜你喜欢
    • 1970-01-01
    • 2017-08-04
    • 1970-01-01
    • 1970-01-01
    • 2020-09-19
    • 2013-07-04
    • 2016-07-29
    • 1970-01-01
    • 2017-08-13
    相关资源
    最近更新 更多