结合rotate与translateY的JS requestAnimationFrame动画逐渐减速停止的问题求助
结合rotate与translateY的JS requestAnimationFrame动画逐渐减速停止的问题求助
完整可复现代码
HTML
<button class='button'>rerun</button> <div class="box"></div>
CSS
.box { margin-left: 300px; width: 10px; height: 10px; background-color: black; transform: rotate(15deg); }
JavaScript
const box = document.querySelector('.box'); let id = undefined; function animateTest() { const style = window.getComputedStyle(box); const matrix = new DOMMatrixReadOnly(style.transform); const translateY = matrix.m42 + 2; box.style.transform = `rotate(12deg) translateY(${translateY}px)`; id = requestAnimationFrame(() => animateTest()); } id = requestAnimationFrame(() => animateTest()); let button = document.querySelector('.button'); button.addEventListener('click', function() { cancelAnimationFrame(id); box.style.transform = `rotate(12deg) translateY(0px)`; id = requestAnimationFrame(() => animateTest()); }, false);
问题说明
我试着让一个小方块沿着12度的方向移动,所以给它同时设置了rotate(12deg)和translateY的动画,但运行一会儿之后,它就停下来不动了。
我感觉requestAnimationFrame应该还在正常调用,但translateY的效果好像失效了——如果我去掉rotate(..)的话,这个动画就能一直正常跑下去。
想请教一下:为什么加上旋转之后,动画会慢慢减速直到停止?有没有办法让它保持正常移动不停止呢?
简化示例(更清晰复现问题)
HTML
<div class="box"> </div>
CSS
.box { margin-left: 300px; width: 10px; height: 10px; background-color: black; transform: rotate(15deg); }
JavaScript
let box = document.querySelector('.box'); function animate() { const style = window.getComputedStyle(box); const matrix = new DOMMatrixReadOnly(style.transform); const translateY = matrix.m42 + 2; box.style.transform = `rotate(12deg) translateY(${translateY}px)`; requestAnimationFrame(() => animate()); } requestAnimationFrame(() => animate());
备注:内容来源于stack exchange,提问作者Sidharth Bajpai
相关产品推荐
相关产品推荐

