gpt4 book ai didi

javascript - 如何修复在 JavaScript 中使用 ctx.lineTo 显示为奇怪形状的六边形?

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

我正在尝试在 Canvas 上创建一个六边形。我成功绘制了一个形状,但不是正确的形状。我使用相同的代码片段制作了一个三 Angular 形,只是更改了边数。

看起来六边形的每条线都是从同一点绘制的,而不是从最后绘制的点绘制的。

我正在遵循涉及创建这些形状的在线教程。我复制并粘贴了视频中那个人所做的事情,然后准确地输入了他所做的事情。我在视频中多次回顾,试图找出我是否错过了什么。

在代码中,是我用于创建六边形的整个类。有些东西正在被渲染和绘制,但它的形状不正确。

我尝试更改一些数字,并查看 ctx.lineTo 看看我是否做错了什么。当他创建这些形状时,我在视频中来回走动,他的作品就成功了。我确信我拥有与视频中用于创建六边形的代码相同的代码。

class Asteroid {
constructor(x, y) {
this.visible = true;
this.x = Math.floor(Math.random() * canvasWidth);
this.y = Math.floor(Math.random() * canvasHeight);
this.speed = 1;
this.radius = 50;
this.angle = Math.floor(Math.random() * 359);
this.strokeColor = gameColor;
}
Update() {
let radians = (this.angle / Math.PI) * 180;
this.x += Math.cos(radians) * this.speed;
this.y += Math.sin(radians) * this.speed;
if (this.x < this.radius) {
this.x = canvas.width;
}
if (this.x > canvas.width) {
this.x = this.radius;
}
if (this.y < this.radius) {
this.y = canvas.height;
}
if (this.y > canvas.height) {
this.y = this.radius;
}
}
Draw() {
ctx.beginPath();
let vertAngle = (Math.PI * 2) / 6;
var radians = (this.angle / Math.PI) * 180;
for (let i = 0; i < 6; i++) {
ctx.lineTo(
this.x - this.radius * Math.cos(vertAngle * i + radians),
this.y - this.radius * Math.sin(vertAngle * i + radians)
);
ctx.closePath();
ctx.stroke();
}
}
}

我希望形状是正六边形,但相反,我得到的形状是每条线都是从一个点绘制的,就像一把扇子或一片叶子。

最佳答案

仅在 for 之后调用 closePath (这是一条在子路径中输入点的线,因此所有线都指向您获得的第一个点)和 lines 一次循环

for (let i = 0; i < 6; i++) {
ctx.lineTo(
this.x - this.radius * Math.cos(vertAngle * i + radians),
this.y - this.radius * Math.sin(vertAngle * i + radians)
);
}
// once all the points have been drawn
ctx.closePath(); // Last closing line
ctx.stroke(); // paint

关于javascript - 如何修复在 JavaScript 中使用 ctx.lineTo 显示为奇怪形状的六边形?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57683142/

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