gpt4 book ai didi

javascript - 如何在 Javascript 中使用 for 循环绘制完整的多边形?

转载 作者:行者123 更新时间:2023-11-28 17:02:28 26 4
gpt4 key购买 nike

所以我尝试利用 HTML 的 Canvas 来绘制凸多边形。

在下面的代码中,t2 是一个点数组(我已经声明了该类,代码可以正常工作,getX() 返回 X,getY() 返回 Y。)

绘图函数一直有效,直到到达 for 循环之后的代码为止。我想画一条连接第一个点和最后一个点的线,但由于某种原因,它没有执行。

var i;
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.beginPath();
for(i = 0; i<t2.length-2; i++){
var t3 = t2[i];
var t4 = t2[i+1];


ctx.moveTo(t3.getX(), t3.getY());
ctx.lineTo(t4.getX(), t4.getY());
ctx.stroke();
}
var t5 = t2[t2.length-1];
var t6 = t2[0];



ctx.moveTo(t5.getX(), t5.getY());
ctx.lineTo(t6.getX(), t6.getY());
ctx.stroke();

Canvas 应该显示一条连接点 t5 和 t6 的线,但什么也没有发生。 for 循环内的所有内容都有效,但之后的所有内容都无效。

最佳答案

closePath() 是你的 friend ...请参阅:https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/closePath

没有工作示例,这里只是对您需要的粗略猜测,并进行了优化。

let c = document.getElementById("myCanvas");
let ctx = c.getContext("2d");
//Start the path.
ctx.beginPath();
//Move to the initial vector.
ctx.moveTo(t2[0].getX(), t2[0].getY());
//Loop through the rest of the vectors skipping the first one.
for(let i = 1; i < t2.length; i++){
//Add a line to the path. This always originates from the previous lineTo end vector.
ctx.lineTo(t2[i].getX(), t2[i].getY());
}
//closePath() attempts to draw a line from the last vector to the first vector in the current path.
ctx.closePath();
//Stroke.
ctx.stroke();

关于javascript - 如何在 Javascript 中使用 for 循环绘制完整的多边形?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56961321/

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