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?
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.
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.
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.
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:
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With