I'm working on a map feature which should allow the user to drag rotate the map with the mouse.
This is the code of my mousedown event:
rotate.addEventListener('mousemove', (e) => {
const elem = e.target;
if (mouseDown) {
const boundingRect = elem.getBoundingClientRect();
const center_x = boundingRect.left + boundingRect.width / 2;
const center_y = boundingRect.top + boundingRect.height / 2;
const mouse_x = e.pageX;
const mouse_y = e.pageY;
const radians = Math.atan2(mouse_x - center_x, mouse_y - center_y);
const degree = radians * (180 / Math.PI) * -1 + 90;
rotate.style.transform = `rotate(${degree}deg)`;
}
});
And here is the fiddle of the example: https://jsfiddle.net/8uexv2cp/3/.
So as you can see, it's kind of working. The problem is that if you start dragging in the top left corner, the element spins around (after this has happened it seems to be working as it should). Ideally I'd want it to just start rotating from the point that i select with the mouse and not having it flick around at the start.
What am I missing here?
I'd be happy to hear your thoughts about this.
Thanks