gpt4 book ai didi

javascript - 使用 lineTo 和圆弧绘制线段和圆 - 填充问题

转载 作者:行者123 更新时间:2023-12-03 10:10:31 25 4
gpt4 key购买 nike

我尝试使用 HTML5 Canvas 制作动画,在其中绘制 3 个片段的位置,每个片段用一个圆圈连接起来。

每个圆的位置由 (x1,y1)、(x2,y2) 和 (x3,y3) 确定。

这是我的代码片段:

      context.fillStyle = 'white';
context.fillRect(0, 0, 400, 320);

context.beginPath();
context.moveTo(x0, y0);
context.lineTo(x1, y1);
context.lineTo(x2, y2);
context.lineTo(x3, y3);
context.strokeStyle = 'black';
context.stroke();

context.beginPath();
context.arc(x1, y1, radius, 0, 2*Math.PI, true);
context.arc(x2, y2, radius, 0, 2*Math.PI, true);
context.arc(x3, y3, radius, 0, 2*Math.PI, true);
context.fillStyle = 'blue';
context.fill();

下面是这些段的起始位置:

(x0,y0) 是顶点坐标,在动画过程中不会改变。

现在,经过一些迭代,我得到了下图:

如您所见,我的代码填充了 3 个点 (x1,y1)、(x2,y2) 和 (x3,y3) 之间的三 Angular 形。

我不想填充这个,我只想绘制 3 个线段并为每次迭代仅填充 3 个圆圈。

上面的代码片段有什么问题?

感谢您的帮助

最佳答案

问题

arc() 只是一条路径,显然是圆形的,但有两个开口端。这会导致它附加到前一个路径点。当发出 fill() 时,主路径关闭,导致第一个圆弧终点连接到第一个圆弧起点。

解决方案

您可以通过为弧创建子路径来解决它。为从 Angular 0 开始的每个弧插入 moveTo() (同时删除 CCW 的最后一个 bool 值,以便它按顺时针方向绘制)。当我们处理子路径时调用 closePath() 将导致子路径关闭末端,这在我们的情况下很好,因为我们可以使用 moveTo() 关闭起点集恰好与圆弧的起点对应,然后连接到圆弧的终点。

示例

 context.beginPath();

context.moveTo(x1 + radius, y1); // create a new sub-path
context.arc(x1, y1, radius, 0, 2*Math.PI);
context.closePath(); // closes the current sub-path

context.moveTo(x2 + radius, y2); // create a new sub-path
context.arc(x2, y2, radius, 0, 2*Math.PI);
context.closePath(); // closes the current sub-path

context.moveTo(x3 + radius, y3); // create a new sub-path
context.arc(x3, y3, radius, 0, 2*Math.PI);
context.closePath(); // closes the current sub-path

// fill all sub-paths
context.fillStyle = 'blue';
context.fill(); // would normally close the main path, but now we only have sub-paths

关于javascript - 使用 lineTo 和圆弧绘制线段和圆 - 填充问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30136871/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com