Canvas, drawing a line segment

2019-08-20 04:56发布

问题:

My trigonometry is more than weak, and therefore I do not know how to draw a line segment shorter than full lines start point and end point.

http://jsfiddle.net/psycketom/TUyJb/

What I have tried, is, subtract from start point a fraction of target point, but it results in a wrong line.

/* 
 * this is an excerpt from fiddle, that shows
 * the actual calculation functions I have implemented
 */
var target = {
    x : width / 2 + 60,
    y : 20
};

var start = {
    x : width / 2,
    y : height
};

var current = {
    x : 0,
    y : 0
};

var growth = 0.5;

current.x = start.x - (target.x * growth);
current.y = start.y - (target.y * growth);

My bet is that I have to use sin / cos or something else from the trigonometry branch to get it right. But, since my trigonometry is not even rusty, but weak in general, I'm stuck.

How do I draw a proper line to target?

回答1:

If I understand you correctly, then this should give you what you're looking for:

current.x = start.x + (target.x - start.x) * growth;
current.y = start.y + (target.y - start.y) * growth;


回答2:

The equation is a linear interpolate, its the same as linear easing. You take the delta of the start and end (min and max), multiply it by a percent (the normal) of how far along delta you are and then you add it back to the start value. Incredibly essential algorithm :)