在画布上从两个x,y点和一个中心x,y点绘制圆弧

时间:2015-06-03 15:45:41

标签: javascript html5-canvas trigonometry

我试图从两个点(X,Y线)绘制弧线。

但我无法弄清楚如何做到这一点,以便我可以指定起始角度和结束角度

我得到了中心点(p2),半径= r。起点(p1)和终点(p3)。 如下图所示 What I have

我想做的是使用弧线绘制如下所示的圆线

What I wanna have

我在这个主题上发现的只是弧从0到2 * Math.PI的例子。

ctx.arc(100,75,50,0,2*Math.PI);

喜欢这个。我无法找到一种可以使用p1和p3代替这些数字的方法。任何人都可以解释这是如何工作的,也许可以解释我如何解决这个问题?

2 个答案:

答案 0 :(得分:1)

arc()方法仅适用于角度,因此必须根据点的位置和到中心的距离来转换点(距离,表示半径,在这种情况下,两者都必须相同)。

signature of arc()是:

  

void arc(无限制的双x,
  不受限制的双y,
  无限制的双半径,
  无限制的双重启动角度,
  不受限制的双端角度,
  可选boolean anticlockwise = false);

您可以通过简单的三角函数找到从中心P2到P1 / P3的两个角度:

var startAngle = Math.atan2(p1.y - p2.y, p1.x - p2.x),
    endAngle   = Math.atan2(p3.y - p2.y, p3.x - p2.x);

现在可以将这些输入到弧方法中,假设半径已知:

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

如果半径未知但已知相同,则可以执行以下操作:

var diffX = p1.x - p2.x,
    diffY = p1.y - p2.y,
    radius = Math.abs(Math.sqrt(diffX*diffX + diffY*diffY));

实施例

var p2 = {x: 100   , y: 100   },
    p1 = {x: 111, y:  30.9},
    p3 = {x: 149.5 , y:  149.5},
    diffX = p1.x - p2.x,
    diffY = p1.y - p2.y,
    radius = Math.abs(Math.sqrt(diffX*diffX + diffY*diffY)),
    startAngle = Math.atan2(diffY, diffX),
    endAngle   = Math.atan2(p3.y - p2.y, p3.x - p2.x),
    ctx = document.querySelector("canvas").getContext("2d");

// arc
ctx.arc(p2.x, p2.y, radius, startAngle, endAngle, false);
ctx.stroke();

// points / lines helpers:
ctx.fillRect(p1.x - 2, p1.y - 2, 4, 4);
ctx.fillRect(p2.x - 2, p2.y - 2, 4, 4);
ctx.fillRect(p3.x - 2, p3.y - 2, 4, 4);
ctx.beginPath();
ctx.moveTo(p1.x, p1.y);
ctx.lineTo(p2.x, p2.x);
ctx.lineTo(p3.x, p3.x);
ctx.strokeStyle = "#999";
ctx.stroke();
<canvas height=180></canvas>

结果wo / helper lines

var p2 = {x: 100   , y: 100   },
    p1 = {x: 111, y:  30.9},
    p3 = {x: 149.5 , y:  149.5},
    diffX = p1.x - p2.x,
    diffY = p1.y - p2.y,
    radius = Math.abs(Math.sqrt(diffX*diffX + diffY*diffY)),
    startAngle = Math.atan2(diffY, diffX),
    endAngle   = Math.atan2(p3.y - p2.y, p3.x - p2.x),
    ctx = document.querySelector("canvas").getContext("2d");

// arc
ctx.arc(p2.x, p2.y, radius, startAngle, endAngle, false);
ctx.stroke();
<canvas height=180></canvas>

答案 1 :(得分:0)

ctx.arc(100,75,50,0,2*Math.PI);

这里前两个参数是点p2 x,y坐标,第三个参数是圆r的半径。 第四和第五个参数是弧的起始角和终止角。

让m21为连接point1(x1,y1)和point2(x2,y2)的线的斜率

m21 =(y2-y1)/(x2-x1)

令m21为连接point3(x3,y3)和point2(x2,y2)的线的斜率

m23 =(y2-y3)/(x2-x3)

ctx.arc(100, 75, 50, Math.atan(m21), Math.atan(m23), true)

会这样做。

如果point2是原点,则解决方案更简单。

ctx.arc(100, 75, 50, Math.atan2(x1,y1), Math.atan2(x3,y3), true)