1
1

三角関数を使わず、単純な積和で円を描く

Posted at

座標の回転

\begin{eqnarray}
x' & = & x \cos{ \theta } - y \sin{ \theta } \\
y' & = & y \cos{ \theta } + x \sin{ \theta } \\
\end{eqnarray}

で $\theta$ が十分小さいとき

\begin{eqnarray}
\cos{ \theta } & \fallingdotseq & 1 \\
\sin{ \theta } & \fallingdotseq & \theta \\
x' & = & x - y\ \theta \\
y' & = & y + x\ \theta \\
\end{eqnarray}

の計算で円描画が可能という記事を約40年くらい前に見た。16 ビット整数を使った演算だと精度が足りず、一周すると元のドットに戻ってこなかった。今なら倍精度浮動小数演算が使えるので試してみる。

JavaScript
function drawCircle(ctx, x, y, r) {
    const cnt = Math.trunc(Math.PI * 2 * r);
    const ir = 1 / r;
    let px = r;
    let py = 0;

    ctx.beginPath();
    ctx.moveTo(x + px, y + py);
    for (let n = 0; n < cnt; n++) {
        px -= py * ir;
        py += px * ir;
        ctx.lineTo(x + px, y + py);
    }
    ctx.closePath();
    ctx.stroke();
}

赤色で Canvas API の arc() を使って円を描いて、青色の drawCircle() を重ねています。

See the Pen 円描画テスト by Ikiuo (@ikiuo) on CodePen.

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1