Computing the angle between two points seems inconsistent with regards to DOM rotation
I've written code to compute the angle between two points. I use the HTML canvas to plot a line between points and I also display a DOM element featuring an arrow character which I rotate to indicate the direction of the vector. I'm unclear why it's necessary to add 270 degrees to correct the position of the arrow.
See this line below: radians += (3 * Math.PI / 2); // why 270 degrees?
class Vector {
constructor(x=0, y=0) {
this.x = x;
this.y = y;
}
angleFromVectors(anchor, point) {
return Math.atan2(anchor.y - point.y, anchor.x - point.x);
}
draw(v1, v2) {
let canvas = document.getElementById('canvas');
if (canvas.getContext) {
let ctx = canvas.getContext('2d');
ctx.moveTo(v1.x, v1.y);
ctx.lineTo(v2.x, v2.y)
ctx.stroke();
}
}
rotateArrow(degrees) {
let arrow = document.getElementById('arrow');
arrow.style.webkitTransform = 'rotate('+ degrees + 'deg)';
}
}
let v1 = new Vector(180, 180);
let v2 = new Vector(100, 190);
let vector = new Vector();
let radians = vector.angleFromVectors(v1, v2);
radians += (3 * Math.PI / 2); // why 270 degrees?
let degrees = radians * (180 / Math.PI);
console.log(`radians: ${radians}, degrees: ${degrees}`);
vector.draw(v1, v2);
vector.rotateArrow(degrees);
Codepen here: https://codepen.io/cjus/pen/bzKvwO
The arrow is the character ⬆
. Since it points up, if you want it to point left, you need to rotate it. You could also rotate it -90deg
.
By the way you're actually rotating it 262.875deg
.