我想创建一个工时。起始位置为0 deg
。如果我单击一个按钮,工时会随着动画旋转到X deg
,并停留在X deg
中
下次,我单击按钮,开始新的旋转动画,工时从X deg
旋转到X + Y deg
,而不是开始0 deg
。这种操作是怎么可能的?
您可以获得计算的角度,将其递增,然后使用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>