两点之间的圆弧:在顶部设置角度“0”

Arc between two points: set angle "0" on top

我在 Javascript 中写了一个绘制圆弧的函数。它基于 Bresenham 圆算法,在绘制点时,我检查它们是否在初始角度和最终角度之间。

它工作正常,但角度“0”在圆的 "far left" 一侧,而我希望它在顶部,同时仍按顺时针方向计算角度。这该怎么做?谢谢

const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');


function pset(x, y) {
  ctx.fillRect(x, y, 1, 1);
}

function arc (x, y, rd, a1 = 0, a2 = 360) {
    let xx = rd;
    let yy = 0;
    let radiusError = 1 - xx;

    function inAngle(x1, y1) {
        const deltaY = y1 - y;
        const deltaX = x1 - x;
        const angleInDegrees = (Math.atan2(deltaY, deltaX) * 180 / Math.PI) + 180;

        return angleInDegrees >= a1 && angleInDegrees <= a2;
    }

    while (xx >= yy) {
        if (inAngle( xx + x,  yy + y)) pset( xx + x,  yy + y);
        if (inAngle( yy + x,  xx + y)) pset( yy + x,  xx + y);
        if (inAngle(-xx + x,  yy + y)) pset(-xx + x,  yy + y);
        if (inAngle(-yy + x,  xx + y)) pset(-yy + x,  xx + y);
        if (inAngle(-xx + x, -yy + y)) pset(-xx + x, -yy + y);
        if (inAngle(-yy + x, -xx + y)) pset(-yy + x, -xx + y);
        if (inAngle( xx + x, -yy + y)) pset( xx + x, -yy + y);
        if (inAngle( yy + x, -xx + y)) pset( yy + x, -xx + y);

        yy++;

        if (radiusError < 0) {
            radiusError += 2 * yy + 1;
        }
        else {
            xx--;
            radiusError+= 2 * (yy - xx + 1);
        }
    }
}

arc(50, 50, 20, 0, 45);
arc(50, 70, 20, 0, 90);
arc(50, 90, 20, 0, 180);
<canvas width="128" height="128" id="canvas"/>

只需将以下两行添加到 arc 函数的开头:

a1 += 90;
a2 += 90;

const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');


function pset(x, y) {
  ctx.fillRect(x, y, 1, 1);
}

function arc (x, y, rd, a1 = 0, a2 = 360) {
    a1 += 90; // add this line
    a2 += 90; // add this line
    let xx = rd;
    let yy = 0;
    let radiusError = 1 - xx;

    function inAngle(x1, y1) {
        const deltaY = y1 - y;
        const deltaX = x1 - x;
        const angleInDegrees = (Math.atan2(deltaY, deltaX) * 180 / Math.PI) + 180;

        return angleInDegrees >= a1 && angleInDegrees <= a2;
    }

    while (xx >= yy) {
        if (inAngle( xx + x,  yy + y)) pset( xx + x,  yy + y);
        if (inAngle( yy + x,  xx + y)) pset( yy + x,  xx + y);
        if (inAngle(-xx + x,  yy + y)) pset(-xx + x,  yy + y);
        if (inAngle(-yy + x,  xx + y)) pset(-yy + x,  xx + y);
        if (inAngle(-xx + x, -yy + y)) pset(-xx + x, -yy + y);
        if (inAngle(-yy + x, -xx + y)) pset(-yy + x, -xx + y);
        if (inAngle( xx + x, -yy + y)) pset( xx + x, -yy + y);
        if (inAngle( yy + x, -xx + y)) pset( yy + x, -xx + y);

        yy++;

        if (radiusError < 0) {
            radiusError += 2 * yy + 1;
        }
        else {
            xx--;
            radiusError+= 2 * (yy - xx + 1);
        }
    }
}

arc(50, 50, 20, 0, 45);
arc(50, 70, 20, 0, 90);
arc(50, 90, 20, 0, 180);
<canvas width="128" height="128" id="canvas"/>