我需要以以下方式画一条线:
目前,它将仅以代码绘制,而无需用户输入。
我的问题是,如果逐点绘制垂直线,该如何绘制? (显然是这样,因为使用贝塞尔曲线的绘图不会给我以某种方式影响绘图的可能性)。
我找到的最接近的答案可能是this one,但是我无法逆转方程式以得出C。而且,由于没有提及装饰的长度,因此我认为这将无法正常工作。
最佳答案
找到与另一个垂直的线段非常容易。
假设我们有A,B点。
计算 vector AB。
对其进行归一化以计算NAB(==“相同” vector ,但长度为1)。
然后,如果 vector 具有(x,y)作为坐标,则其法线 vector 具有(-y,x)作为坐标,因此
您可以轻松拥有PNAB(PNAB =与AB垂直的法向 vector )。
// vector AB
var ABx = B.x - A.x ;
var ABy = B.y - A.y ;
var ABLength = Math.sqrt( ABx*ABx + ABy*ABy );
// normalized vector AB
var NABx = ABx / ABLength;
var NABy = ABy / ABLength;
// Perpendicular + normalized vector.
var PNABx = -NABy ;
var PNABy = NABx ;
最后一步是计算D,该点位于A的距离l处:只需将l * PNAB加到A上:
// compute D = A + l * PNAB
var Dx = A.x + l* PNAB.x;
var Dy = A.y + l *PNAB.y;
更新了JSBIN:
http://jsbin.com/bojozibuvu/1/edit?js,output
编辑:
第二步是按规则的距离绘制装饰,因为现在是圣诞节,所以我要这样做:
http://jsbin.com/gavebucadu/1/edit?js,console,output
function drawDecoratedSegment(A, B, l, runningLength) {
// vector AB
var ABx = B.x - A.x;
var ABy = B.y - A.y;
var ABLength = Math.sqrt(ABx * ABx + ABy * ABy);
// normalized vector AB
var NABx = ABx / ABLength;
var NABy = ABy / ABLength;
// Perpendicular + normalized vector.
var PNAB = { x: -NABy, y: NABx };
//
var C = { x: 0, y: 0 };
var D = { x: 0, y: 0 };
//
drawSegment(A, B);
// end length of drawn segment
var endLength = runningLength + ABLength;
// while we can draw a decoration on this line
while (lastDecorationPos + decorationSpacing < endLength) {
// compute relative position of decoration.
var decRelPos = (lastDecorationPos + decorationSpacing) - runningLength;
// compute C, the start point of decoration
C.x = A.x + decRelPos * NABx;
C.y = A.y + decRelPos * NABy;
// compute D, the end point of decoration
D.x = C.x + l * PNAB.x;
D.y = C.y + l * PNAB.y;
// draw
drawSegment(C, D);
// iterate
lastDecorationPos += decorationSpacing;
}
return ABLength;
}