Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript: figure out point Y by angle and distance

In my project, I would like to draw a line from point X to point Y.

While I know the position of point X, I only know the angle and the distance of point Y.

So my problem is to get the coordinates of point Y by the angle (from point X) and the distance.

I am using JavaScript for this project and don't want to use any graphical library.


For example:

  • point X (10;20)

  • point Y (10° & 200px from point X)

It is probably pretty basic math, but I have no clue how to do it.

like image 837
T.Lange Avatar asked Jul 03 '13 19:07

T.Lange


People also ask

How do you find the angle between two points in Javascript?

The Math. atan2() function returns the angle in the plane (in radians) between the positive x-axis and the ray from (0, 0) to the point (x, y), for Math. atan2(y, x) .


2 Answers

js> Math.cos(10*Math.PI/180) * 200 + 10
206.9615506024416
js> Math.sin(10*Math.PI/180) * 200 + 20
54.729635533386066

Y is at (207, 55).

like image 120
Ignacio Vazquez-Abrams Avatar answered Oct 29 '22 12:10

Ignacio Vazquez-Abrams


Here is a code snippet that wraps @IgnacioVazquez-Abrams's answer into a function with an example of how to use it:

function findNewPoint(x, y, angle, distance) {
    var result = {};

    result.x = Math.round(Math.cos(angle * Math.PI / 180) * distance + x);
    result.y = Math.round(Math.sin(angle * Math.PI / 180) * distance + y);

    return result;
}

var newPoint = findNewPoint(10, 20, 10, 200);
console.log('newPoint:', newPoint);
like image 34
codershop Avatar answered Oct 29 '22 14:10

codershop