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...
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.