我在Javascript中编写了一个绘制弧的函数。它基于Bresenham圆算法,并在绘制点时,检查它们是否在初始角度和最终角度之间。
它运作正常,但角度" 0"在最左边"圆圈的一侧,虽然我仍然希望它在顶部,同时仍然顺时针计算角度。这该怎么做?感谢
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);
&#13;
<canvas width="128" height="128" id="canvas"/>
&#13;
答案 0 :(得分:2)
只需将以下两行添加到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"/>