Reputation: 13367
http://jsfiddle.net/psycketom/TUyJb/3/
I recently asked a question to calculate the endpoint of a line in canvas based on percentage: Canvas, drawing a line segment
Now, I am stuck with how to calculate X percentage in the line from startpoint to be used as actual startpoint.
In the fiddle above, I have tried to mirror endpoints:
growth = 0.2;
// calculate line endpoint
current.x = start.x + (target.x - start.x) * growth;
current.y = start.y + (target.y - start.y) * growth;
// calculate line startpoint
scurrent.x = start.x + (start.x - target.x) * growth;
scurrent.y = start.y + (start.y - target.y) * growth;
But that does not seem to do what I want it to do.
My real goal is to make a function, that would draw a line:
Upvotes: 3
Views: 970
Reputation: 2615
what you are stated as the endpoint is actually your "startpoint":
// calculate line "endpoint"
current.x = start.x + (target.x - start.x) * growth;
current.y = start.y + (target.y - start.y) * growth;
here is a function that returns a waypoint:
// start and end are points with .x and .y
// q is a number between 0.0 and 1.0
var waypoint = function (start, end, q) {
return {
x: start.x + (end.x - start.x) * q,
y: start.y + (end.y - start.y) * q
};
}
now you can calculate waypoint wherever you want:
var start = {x: 10, y: 20},
end = {x: 120, y: 70},
a = waypoint(start, end, 0.2),
b = waypoint(start, end, 0.8);
a
and b
will be point 20% in from either end of the original line.
Upvotes: 3