Let's say I have two points which I know: x1,y1 and x2,y2. I know I can easily calculate the length of this line with Pythagorean, but what if I want to calculate a shortened version of the line. For example, I would like the x,y coordinates 10 pixels toward the next point. Is there a simple formula for finding any new point on an angled line?
OK, here is the solution as a JavaScript function. I've intentionally made this extra verbose for explanatory purposes. As the comments below suggested, you have to find the angle first, then calculate the sides with a new hypotenuse.
/**
* Calculates length of a line on Cartesian grid, then returns point that is X number of pixels down the line.
*
* @param {Number} fromX - starting x point
* @param {Number} fromY - starting y point
* @param {Number} toX - ending x point for vector
* @param {Number} toY - ending y point for vector
* @param {Number} pxDistance - Number of pixels down line toward ending point to return
* @return {Object} Returns x/y coords of point on line based on number of pixels given
*/
function stortenLineDistance(fromX, fromY, toX, toY, pxDistance){
//if line is vertical
if(fromX === toX)
return {x: toX, y: toY > fromY ? fromY + pxDistance : fromY - pxDistance};
//if line is horizontal
if(fromY === toY)
return {y: toY, x: toX > fromX ? fromX + pxDistance : fromX - pxDistance};
//get each side of original triangle length
var adjacent = toY - fromY;
var opposite = toX - fromX;
var hypotenuse = Math.sqrt(Math.pow(opposite, 2) + Math.pow(adjacent,2));
//find the angle
var angle = Math.acos(adjacent/hypotenuse);
//calculate new opposite and adjacent sides
var newOpposite = Math.sin(angle) * pxDistance;
var newAdjacent = Math.cos(angle) * pxDistance;
//calculate new x/y, see which direction it's going
var y = fromY - newAdjacent,
x = fromX + newOpposite;
return {y: y, x: x};
}
EDIT: Wow, Stackoverflow is brutal. Feel free to delete this question if you wish, though I think it could be helpful to someone stuck on the same issue down the line. Maybe I'm wrong.
At any rate, thanks to commenters for help.
I've created a fiddle that utilizes a ratio of corresponding sides. Adjust variable smallerLen
to any unit to see the point move across the line.
http://jsfiddle.net/3SY8v/
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