【问题标题】:Unwanted half circle when trying to draw quarter circles尝试绘制四分之一圆时不需要的半圆
【发布时间】:2021-11-20 04:39:04
【问题描述】:

我正在尝试使用 HTML5 中的 canvas 元素创建斐波那契螺旋线。

这是我的绘图代码,斐波那契数列中的每个数字都会调用此函数。 Side 是正方形的边长,或当前的斐波那契数。 start 是每个正方形的右下角。

function drawSpiral(side, start) {
  ctx.beginPath();
  ctx.moveTo(start.x, start.y);
  ctx.lineTo(start.x, start.y - side);
  ctx.lineTo(start.x - side, start.y - side);
  ctx.lineTo(start.x - side, start.y);
  ctx.lineTo(start.x, start.y);
  ctx.stroke();
  ctx.closePath();

  ctx.beginPath();
  switch (direction) {
    case 0:
      ctx.arc(start.x, start.y - side, side, Math.PI, 1.5 * Math.PI, true);
      break;
    case 1:
      ctx.arc(
        start.x - side,
        start.y - side,
        side,
        1.5 * Math.PI,
        2 * Math.PI,
        true
      );
      break;
    case 2:
      ctx.arc(start.x - side, start.y, side, 2 * Math.PI, Math.PI / 2, true);
      break;
    case 3:
      ctx.arc(start.x, start.y, side, Math.PI / 2, Math.PI, true);
      break;
  }
  ctx.stroke();
  ctx.closePath();
}

方向是一个数字,0 到 4,表示下一个正方形的方向,逆时针 - 0 = 右,1 = 上,...

它可以很好地绘制正方形和圆弧,但它也到处都是半圆形,我不知道为什么。

Screenshot of the issue

【问题讨论】:

  • 对我来说看起来像 3/4 圈,可能是顺时针与逆时针的问题。

标签: javascript html html5-canvas


【解决方案1】:

最后一个参数是“逆时针”,

ctx.arc(x, y, radius, startAngle, endAngle, true);

会做同样的事情

ctx.arc(x, y, rad, endAngle, startAngle);
// note how start and end have been swapped

这是从endAnglestartAngle 的弧线,所以在你的情况下,它会画出一个圆的 3/4:

const ctx = document.querySelector("canvas").getContext("2d");
const startAngle = Math.PI; // 9 o'clock
const endAngle = Math.PI * 1.5; // 12 o'clock

ctx.arc(50, 50, 50, startAngle, endAngle, true);
ctx.strokeStyle = "green";
ctx.stroke();

ctx.beginPath();
ctx.arc(160, 50, 50, endAngle, startAngle);
ctx.strokeStyle = "blue";
ctx.stroke();
<canvas></canvas>

如果您只想跟踪圆的 1/4,则不要设置此参数。

【讨论】:

  • 所以这几乎可以工作。它只画了它应该画的圆的 1/4,但它没有画它应该画的地方。它不是在广场内,而是在广场外。或者,当它应该下降时上升。
  • @TreBabcock 好吧,您的代码中可能还有其他问题。你没有显示传递给函数的参数,我们帮不了你更多,只要记住这两个角度都是相对于 x 轴的,即0 是 3 点钟。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-27
  • 2022-11-29
相关资源
最近更新 更多