Search code examples
javascriptmathcanvas2dline

Moving a Point Along a Line in JavaScript Canvas


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 every frame. How can I do this?


Solution

  • Consider the line (25,35 45,65). The vector from the beginning to the end is (20, 30). To move a point (x,y) in that direction, we could just add that vector:

    V = (20, 30) (x,y) => (x+20, y+30).

    If we start at the beginning of the line, we'll arrive at the end. But that's too big a step. We want something smaller but in the same direction, so we multiply the vector by, say, 0.1:

    V = (2, 3) (x,y) => (x+2, y+3) => (x+4, y+6) => ...

    It's convenient to normalize, that is to make its length 1, which we do by dividing by its length:

    V => V/|V| = (2,3)/sqrt(22 + 32) = (7.21, 10.82)

    Then you can just multiply that by whatever step size you want.