【问题标题】:How do I fix my hexagons that are showing as strange shape with ctx.lineTo in JavaScript?如何修复在 JavaScript 中使用 ctx.lineTo 显示为奇怪形状的六边形?
【发布时间】:2019-08-27 22:56:45
【问题描述】:

我正在尝试在画布上创建一个六边形。我成功地绘制了一个形状,但不是正确的。我使用相同的代码 sn-p 制作了一个三角形,我只是更改了边数。

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

我正在关注有关创建这些形状的在线教程。我复制并粘贴了视频中那个人所做的事情,然后我准确地输入了他所做的事情。我在视频中多次返回,试图弄清楚我是否错过了什么。

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

我尝试更改一些数字,并查看 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();
    }
  }
}

我希望这个形状是一个正六边形,但相反,我得到的形状是每条线都是从一个点开始绘制的,比如扇子或叶子。

【问题讨论】:

    标签: javascript canvas polygon


    【解决方案1】:

    调用closePath(这是一个 lineTo 进入子路径中的点,因此所有行到你得到的第一个点)和stroke 在你的 for 循环之后只调用一次

    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
    

    【讨论】:

    • 谢谢!我快要疯了,想弄清楚。我什至不认为这两个函数在错误的大括号中。
    猜你喜欢
    • 2014-05-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多