从旋转位置开始的Javascript旋转动画

时间:2020-10-27 17:29:57

标签: javascript html jquery css css-animations

我想创建一个工作时间。起始位置为0 deg。如果我单击一个按钮,则时针旋转并显示动画,X deg,然后停留在X deg中。
下一次,我单击该按钮,开始一个新的旋转动画,然后时针从X + Y deg旋转到X deg,而不是开始0 deg。该操作怎么可能?

1 个答案:

答案 0 :(得分:1)

您可以获取计算出的角度,将其递增,然后使用JS更新CSS。

const hand = document.querySelector('.hand'),
      loop = document.querySelector('.loop'),
      refreshRate = 60, tickAngle = 3;

let loopId = null;

const startStop = (e) => {
  if (loopId) {
    clearInterval(loopId); loopId = null;
  } else {
    loopId = setInterval(tick, 1000 / refreshRate);
  }
  loop.textContent = loopId ? 'Stop' : 'Start';
};

const tick = () => {
  const degrees = (getCurrentAngle(hand) + tickAngle) % 360;
  hand.style.transform = `rotate(${degrees}deg)`;
};

// Adapted from:
// https://css-tricks.com/get-value-of-css-rotation-through-javascript/
const getCurrentAngle = (el) => {
  const st = window.getComputedStyle(el, null),
        tr = st.getPropertyValue('-webkit-transform') ||
             st.getPropertyValue('-moz-transform') ||
             st.getPropertyValue('-ms-transform') ||
             st.getPropertyValue('-o-transform') ||
             st.getPropertyValue('transform'),
       [a, b] = tr.match(/^matrix\((.+)\)$/)[1].split(/,\s*/g).map(Number);
  return Math.round(Math.atan2(b, a) * (180 / Math.PI));
};

loop.addEventListener('click', startStop);
.face {
  position: relative;
  border: 0.25em solid black;
  border-radius: 50%;
  width: 8em;
  height: 8em;
}

.hand {
  position: absolute;
  width: 0.25em;
  height: 3.5em;
  background: red;
  left: 4em;
  top: 4em;
  transform-origin: 0.125em 0; /* x = width / 2 */
  transform: rotate(180deg);   /* Start at 0th hour */
}
<div class="face">
  <div class="hand">
  </div>
</div>
<div>
  <button class="loop">Start</button>
</div>

相关问题