How to make css animation of rotation around a full circle

I have an element that sometimes rotates on transform: rotate(). I want to smooth the transition between states using transition: transform. The problem is that degrees in rotate()are always hard-coded between -360and +360, therefore, after one full value of a rounded degree jumps from 359to 0, and the animation makes a full circle back instead of a smooth little animation to the right. Is there a way to make transient work in a "short way"?

Update: the angle is calculated from the position of the camera, so I can’t use the value of unlimited degree right now.

Clarification: I cannot change js code right now, only CSS. So only [0, 360)degrees at this moment. The demo only mimics the situation I am in.

Demo

o = document.querySelector("#arrow");
t = document.querySelector("#text");
angle = 0;
delta = 2;
FULL_TURN = 360;

document.querySelector("html").addEventListener("mousemove", (e) => {
  if (e.buttons === 1) {
    if (e.movementX > 0) {
      angle += delta;
    }
    if (e.movementX < 0) {
      angle -= delta;
    }
    angle %= FULL_TURN;
    o.style.transform = "rotate(" + angle + "deg)";
    t.innerText = angle + "deg";
  }
})
#arrow {
  font-size: 6em;
  width: 150px;
  text-align: center;
  user-select: none;
  transform-origin: 50% 60%;
  transition: transform 0.2s linear;
}
<header>Drag mouse left or right</header>
<span id="text">0deg</span>
<div id="arrow"></div>
Run codeHide result
+4
source share
1 answer

You can just count the “rounds” and add 360 per round to your corner:

value = angle + rounds*360;

See this working example:

o = document.querySelector("#arrow");
t = document.querySelector("#text");
angle = 0;
delta = 2;
FULL_TURN = 360;
rounds = 0;

document.querySelector("html").addEventListener("mousemove", (e)=>{
	if (e.buttons === 1) {
    if (e.movementX > 0) {
       angle += delta;
       if (angle >= 360) rounds++;
    }
    if (e.movementX < 0) {
       angle -= delta;
       if (angle <= -360) rounds--;
    }
    angle %= FULL_TURN;
    value = angle + rounds*360;
    o.style.transform = "rotate(" + value + "deg)";
    t.innerText = angle + "deg";
  }
})
#arrow {
  font-size: 10em;
  width: 150px;
  text-align: center;
  user-select: none;
  transform-origin: 50% 60%;
  transition: transform 0.2s linear;
}

body {
  padding: 10px;
}
header {
  margin-bottom: 10px;
}
<header>Drag mouse left or right</header>
<span id="text">0deg</span>
<div id="arrow"></div>
Run codeHide result
+4
source

Source: https://habr.com/ru/post/1671118/


All Articles