有两个点,我想得到这两个点链接的线中的点。我知道距离是这两点之一。

像这样

http://jsfiddle.net/icai/2pmk3/

var r = new Raphael(document.getElementById('canvas'), 500, 500),
    π = Math.PI;

function angle(a, b) {
    // ATan2(dy , dx) where dy = y2 - y1 and dx = x2 - x1,
    // or ATan(dy / dx)
    return Math.atan2(b.y - a.y, b.x - a.x);
}

function line(opts) {
    var p = r.path([
            "M", opts.x, opts.y,
            "L", opts.x2, opts.y2].join(',')
        ).attr('stroke', opts.color),
        pt = p.getTotalLength(),
        s = p.getPointAtLength(pt - 20),
        e = p.getPointAtLength(pt),
        // perpendicular
        a = π - angle(s, e) + π/2;
        //a = π - ( s.alpha * π / 180 ) + π/2;

    var d = 15,
        x = s.x - d * Math.cos(a),
        y = s.y + d * Math.sin(a),
        x2 = s.x - d * Math.cos(a - π),
        y2 = s.y + d * Math.sin(a - π);

    r.circle(x,y, 2).attr('stroke', '#00F');
    r.circle(x2,y2, 2).attr('stroke', '#0F0');
    var pp = r.path([
            'M', x, y,
            'L', x2, y2,
        ].join(',')).attr('stroke', '#F00');
}

// senkrecht
line({x: 30, y: 30, x2: 30, y2: 200, color: '#000'});
line({x: 60, y: 200, x2: 60, y2: 30, color: '#000'});

// waagerecht
line({x: 150, y: 30, x2: 300, y2: 30, color: '#000'});
line({x: 300, y: 60, x2: 150, y2: 60, color: '#000'});

// diagonal
line({x: 100, y: 100, x2: 200, y2: 200, color: '#000'});
line({x: 200, y: 250, x2: 100, y2: 150, color: '#000'});

// irgendwas
line({x: 300, y: 300, x2: 450, y2: 320, color: '#000'});
line({x: 300, y: 200, x2: 400, y2: 160, color: '#000'});


但我想将绿色点全部放在黑线上。

最佳答案

不确定我从您含糊的文字中得到了正确的答案:


你知道A,B线的2个“端点”点
您想知道距一个点d-far(让它从第一个开始)的d-far线上的C点

所以:

C=A+d*(B-A)/|B-A|

其中A,B,C是向量
d是标量
||是绝对值
因此在2D中:

qx=bx-ax
qy=by-ay
qq=d/sqrt(qx*qx+qy*qy)
cx=ax+qx*qq
cy=ay+qy*qq

关于javascript - 获取直线上形成atan2和距离的点,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/24596949/

10-09 22:22