找到与另一个垂直的段很容易.
假设我们有点A,B.
计算向量AB.
将其标准化以计算NAB(=='相同'向量,但长度为1).
然后,如果向量具有(x,y)作为坐标,则其法向量具有(-y,x)作为坐标,因此可以容易地具有PNAB(PNAB =垂直法线向量到AB).
// 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 ;
Run Code Online (Sandbox Code Playgroud)
最后一步是计算D,即距离为A的点:只需将l*PNAB添加到A:
// compute D = A + l * PNAB
var Dx = A.x + l* PNAB.x;
var Dy = A.y + l *PNAB.y;
Run Code Online (Sandbox Code Playgroud)
更新了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;
}
Run Code Online (Sandbox Code Playgroud)