请看下面的图1(我相信您已经了解这个基本的二维几何,但如果没有这个,我的答案将不完整):
已知点A和B的坐标,我们希望找到一个函数,可以在已知x坐标时用来计算y坐标,使得点(x,y)位于直线上。从图1中可以看出:s = (x3 - x1) / 4
等。x_start = x1 + s(然后x_start += s)
,并使用A-C线的方程计算y坐标y_end = k1*x_start
。这将给出一个位于A-C线上的点,这是您的线的起点。x_end = x2 + s(稍后x_end += s)
y_end = k2*x_end + m2
|x3 - x1| / desired_num_of_lines
条线)。在使用Context2D
时,要始终考虑使用变换(translate
, rotate
, scale
)可以避免一些复杂的数学运算。
通过这些变换,您可以将绘画视为使用笔:您把笔放在哪里?下一步移动到哪里(translate
)?旋转页面(rotate
)?是否靠近或远离页面(scale
)?
在此示例中,您希望从A开始,然后沿AC移动。
在途中的每一步,您都想绘制AB向量。
以下是如何编写此代码的方法。正如您所看到的,这里只涉及简单的向量数学计算。因此,如果您记得AB向量具有(B.x-A.x, B.y-A.y)坐标,则您已经知道了大部分需要的数学运算。
// boilerPlate
var ctx = document.getElementById('cv').getContext('2d');
ctx.strokeStyle = '#000';
// params : Points : {x,y}
var A, B, C;
A = { x: 20, y: 170 };
B = { x: 80, y: 60 };
C = { x: 140, y: 120 };
// param : number of lines to draw.
var stepCount = 5;
// ----------
// compute AB vector = B - A
var AB = { x: B.x - A.x, y: B.y - A.y };
// compute step : ( C - A ) / stepCount
var step = { x: (C.x - A.x) / stepCount, y: (C.y - A.y) / stepCount };
// -- start draw
ctx.save();
// Move pen to A
ctx.translate(A.x, A.y);
for (var i = 0; i <= stepCount; i++) {
// draw AB vector at current position
ctx.lineWidth= ( i==0 || i==stepCount ) ? 2 : 1 ;
drawVector(AB);
// move pen one step further
ctx.translate(step.x, step.y);
}
ctx.restore();
// --
// draws vector V at the current origin ((0,0)) of the context.
function drawVector(V) {
ctx.beginPath();
ctx.moveTo(0, 0);
ctx.lineTo(V.x, V.y);
ctx.stroke();
}
// ----------
// legend
drawPoint(A, 'A');
drawPoint(B, 'B');
drawPoint(C, 'C');
function drawPoint(P, name) {
ctx.beginPath();
ctx.arc(P.x, P.y, 3, 0, 6.28);
ctx.fill();
ctx.strokeText(name, P.x + 6, P.y + 6);
}
<canvas id='cv' width=300 height=200></canvas>
context.beginPath();
context.moveTo(100, 150);
context.lineTo(450, 50);
context.stroke();
context.beginPath();
context.moveTo(150, 200);
context.lineTo((450+50), (50+50));
context.stroke();