Moving a Point Along a Line in JavaScript Canvas

前端 未结 4 848
心在旅途
心在旅途 2020-12-30 07:33

Let\'s say that I have the coordinates of a line (25,35 45,65, 30,85 - It would be a two part line). I need to move a point (car) along that line at a constant distance ever

4条回答
  •  心在旅途
    2020-12-30 07:54

    8 years too late but someone may find this useful. This method is far faster given it doesn't uses stuff like atan, cos, sin and square root of which all are slow.

    function getPositionAlongTheLine(x1, y1, x2, y2, percentage) {
        return {x : x1 * (1.0 - percentage) + x2 * percentage, y : y1 * (1.0 - percentage) + y2 * percentage};
    }
    

    Pass percentage as value between 0 and 1 where 0 is start of the line and 1 being the end.

    var xy = getPositionAlongTheLine(100, 200, 500, 666, 0.5);
    console.log(xy.x, xy.y);
    

提交回复
热议问题