如何计算在移动d距离后具有坐标(x1,y1),(x2,y2)的线的新点(x3,y3),(x4,y4)?

时间:2017-01-09 04:46:43

标签: javascript graph linear-algebra

1 个答案:

答案 0 :(得分:1)

这样的东西?

function lineOffset(x1, y1, x2, y2, d){
    // delta between points
    var dx = x2 - x1;
    var dy = y2 - y1;

    // gradient of line segment
    var dx_dy = dx / dy;
    // inverse (perpendiular line)
    var dy_dx = 1 / dx_dy;

    // point inbetween P1 and P2
    var x12 = (x1 + x2) / 2;
    var y12 = (y1 + y2) / 2;

    // point inbetween P3 and P4
    var x34 = x12 + (d * Math.cos(dy_dx));
    var y34 = y12 + (d * Math.sin(dy_dx));

    // sub 1/2 the line length to get P3
    var x3 = x34 - (dx / 2);
    var y3 = y34 - (dy / 2);

    // add 1/2 the line length to get P4
    var x4 = x34 + (dx / 2);
    var y4 = y34 + (dy / 2);

    return {
        x3: x3,
        y3: y3,
        x4: x4,
        y4: y4
    }
}