用垂直装饰画一条线

Ang*_*ore 2 javascript math geometry canvas

我需要以下列方式画一条线:

例  

目前,它只会在代码中绘制,而不是用户输入.

我的问题是,如果我逐点绘制它,如何将垂线绘制成一条直线?(显然,情况就是如此,因为使用贝塞尔曲线绘制不会让我有可能以某种方式影响绘图).

我找到的最接近的答案可能就是这个,但是我无法反转方程式来推导C.同样没有提到装饰的长度,所以我认为这不会像我想的那样有效.

Gam*_*ist 5

找到与另一个垂直的段很容易.
假设我们有点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)