在画布上画一条线

时间:2015-09-28 03:26:50

标签: line

目前我有这段代码:

sample.beginPath();
sample.moveTo(X1.x,Y1.x );
sample.lineTo(X2.x,Y2.y);
sample.stroke();

sample.beginPath();
sample.arc(X2.x, Y2.y, 4, 0, 2 * Math.PI, false);
sample.fill();
sample.lineWidth = 1;
sample.stroke();

这将创建:

enter image description here

这将指向任何方向。

我想要的是:

enter image description here

注意:

1.There will only be one line, either Line A or B.

2.They will always point from left to right.

3. They are in 45 degrees.

1 个答案:

答案 0 :(得分:0)

看看下图:

enter image description here

(x1,y1)是鼠标的起点。假设鼠标已经移动到右侧(当它向左移动时你必须处理这种情况),新的鼠标坐标将是(x2,y2)。但是,我们不想在(x1,y1)和(x2,y2)之间画线,因为这条线的斜率(角度)不是所需的线。因此,我们必须计算新点 P 的坐标,它们就在我们的行上。 注意:我假设此点的x坐标将等于新的mouse-x坐标x2!

通过这个假设并借助一些基本的二维几何,我们得到:

a = x2 - x1
tan(alpha) = b / a => b = a * tan(alpha)
P.x = x2

P.y坐标的值取决于鼠标是否从起始位置移动向上向下

IF (y1 > y2)
    P.y = y1 - b // Mouse has moved up (drawing shows this scenario)
ELSE
    P.y = y1 + b // Mouse has moved down (not shown in the drawing)

所以我们有一个新的点P,现在你可以简单地绘制(x1,y1)和P之间的线。你还必须处理一些特殊情况,例如如果鼠标移动到起始点的左边。< / p>

为了获得你的P点,你也应该插入你想要的角度(它可以不同于45度,但它必须是正角度 - 你可以得到公式这也适用于负角度。)

相关问题