Warm tip: This article is reproduced from stackoverflow.com, please click
coordinates javascript math svg angle

Get ending line coordinates in javascript based on starting coordinates and predefined angle

发布于 2020-04-05 00:21:48

I have a problem where I draw SVG lines on each click, what I need to do is draw only horizontal/vertical lines (90deg) or 45deg. line. The horizontal/vertical problem I already solved, where I'm stuck is drawing 45deg. line if I know the following information: startCoordX, startCoordY, endCoordX, endCoordY, angle(either positive 45deg or negative -45deg. Basically I need to just tweak the endCoordinates to make them form a +-45deg. angle line with the starting coordinates. So far I am calculating the angle between the two points like this:

angle(startx, starty, endx, endy) {
        var dy = endy - starty;
        var dx = endx - startx;
        var theta = Math.atan2(dy, dx); // range (-PI, PI]
        theta *= 180 / Math.PI; // rads to degs, range (-180, 180]
        //if (theta < 0) theta = 360 + theta; // range [0, 360)
        return Math.abs(theta) > 90 ? theta % 90 : theta;
}

Any ideas how can I achieve this? I need another function that will return me the ending X and Y coordinates in order to draw the line...

Questioner
Kristijan Stefanoski
Viewed
85
Alex L 2020-02-03 16:31

See this answer: https://stackoverflow.com/a/18473154/9792594

function polarToCartesian(centerX, centerY, radius, angleInDegrees) {
  var angleInRadians = (angleInDegrees-90) * Math.PI / 180.0;

  return {
    x: centerX + (radius * Math.cos(angleInRadians)),
    y: centerY + (radius * Math.sin(angleInRadians))
  };
}

With that, you can call it with 45 as the 4th argument, i.e.:

const pos = polarToCartesian(startx, starty, radius, 45)

This requires you to know the radius you want to draw. Or you could get it from your function, like:

angle(startx, starty, endx, endy) {
        const dy = endy - starty;
        const dx = endx - startx;
        const radius = Math.sqrt(dy**2 + dx**2);
        const pos = polarToCartesian(startx, starty, radius, 45);
        let theta = Math.atan2(dy, dx); // range (-PI, PI]
        theta *= 180 / Math.PI; // rads to degs, range (-180, 180]
        //if (theta < 0) theta = 360 + theta; // range [0, 360)
        return Math.abs(theta) > 90 ? theta % 90 : theta;
}

The important lines are const radius = Math.sqrt(dy**2 + dx**2); followed by const pos = polarToCartesian(startx, starty, radius, 45)

I assume you want to change your final return to check if the current theta is closer to 45 than to 0 or 90? And then if so, draw a 45-degree line instead?

Any questions, or if I understood incorrectly your goal, please let me know.