Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 300
Conner Ruhl Avatar asked May 12 '11 22:05

Conner Ruhl


People also ask

How do I move to a specific point in the canvas?

The numbers in the table specify the first browser version that fully supports the method. The moveTo () method moves the path to the specified point in the canvas, without creating a line. Tip: Use the stroke () method to actually draw the path on the canvas.

How do I draw a line to a point in canvas?

The lineTo () method adds a new point and creates a line TO that point FROM the last specified point in the canvas (this method does not draw the line). Tip: Use the stroke () method to actually draw the path on the canvas.

How do I move to a specific point without creating a line?

The moveTo () method moves the path to the specified point in the canvas, without creating a line. Tip: Use the stroke () method to actually draw the path on the canvas.

How to draw a line from the previous point to the point?

Finally, draw a line from the previous point to the point (x,y) by calling the lineTo (x,y) method. If you want to stroke the line with the strokeStyle, you can call the stroke () method after calling the lineTo (x,y) method. To set the width for a line, you use the lineWidth property of the 2D drawing context before calling stroke () method:


1 Answers

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);
like image 124
John Avatar answered Oct 19 '22 03:10

John