I am trying to find fixed degrees of rotation of an image in a html page. The following code from the original author works perfectly for rotating the image.
I like to get the degrees of rotation from the initial starting point (which is 0), preferably limited to 0-360, whenever the image is rotated (multiple times).
HTML
<body>
<span>
<img class="rotate" id="img01" src="wheel.png" alt="image" />
</span>
</body>
Javascript code
const rotate = (EL) => {
let ang = 0;
let angStart = 0;
let isStart = false;
const angXY = (ev) => {
const bcr = EL.getBoundingClientRect();
const radius = bcr.width / 2;
const { clientX, clientY } = ev.touches ? ev.touches[0] : ev;
const y = clientY - bcr.top - radius; // y from center
const x = clientX - bcr.left - radius; // x from center
return Math.atan2(y, x);
};
const mousedown = (ev) => {
isStart = true;
angStart = angXY(ev) - ang;
};
const mousemove = (ev) => {
if (!isStart) return;
ev.preventDefault();
ang = angXY(ev) - angStart;
EL.style.transform = `rotateZ(${ang}rad)`;
};
const mouseup = () => {
console.log('mouse up to ', ang, ', ', getDegrees(ang));
isStart = false;
};
EL.addEventListener("mousedown", mousedown);
document.addEventListener("mousemove", mousemove);
document.addEventListener("mouseup", mouseup);
};
function getDegrees(ang) {
/* let deg = (ang * (180 / Math.PI) * -1) + 90;
while (deg > 360) {
deg -= 360;
}
while (deg < -360) {
deg += 360;
}
return deg; */
return ang * (180.0 / 3.141592653589793238463)
}
document.querySelectorAll(".rotate").forEach(rotate);