繁体   English   中英

如何在 JavaScript 中的 animation 之后保存 object position?

[英]How to save object position after animation in JavaScript?

我正在尝试为 object 制作动画,在该游戏中球应该在按下用户按钮时向上、向右、向左和向下移动。 我试图通过在球上使用.animate() function 来实现这一点。 但在每次 animation 事件之后,球会重置为其初始 position 并且不会继续从其“新”position 移动。 有没有办法做到这一点?

为简单起见,以下是我的精简代码片段:

 /* Animation */ var item = document.getElementById('item'); var anim; function myMoveLeft(){ anim=item.animate([ // keyframes { transform: 'translateX(0px)' }, { transform: 'translateX(-60px)' } ], { duration: 1000, iterations: 1 }); } function myMoveDown(){ anim=item.animate([ // keyframes { transform: 'translateY(0px)' }, { transform: 'translateY(60px)' } ], { duration: 1000, iterations: 1 }); // anim.onfinish(()=>{console.log("onfinish ran")}) } item.addEventListener('animationend', () => { console.log('Animation ended'); });
 button{ display:inline-block; height:40px; width:80px; } #myContainer { width: 400px; height: 400px; position: relative; background: lightgray; } #item { background: orange; position: absolute; right:30px; top:30px; height: 30px; width: 30px; border-radius:50%; }
 <p> <button onclick="myMoveLeft()">Left</button> <button onclick="myMoveDown()">Down</button> </p> <div id ="myContainer"> <div id="item"></div> </div>

正如所见,我已经尝试过使用.onfinish() 和事件监听器'animationend',希望我可以更新新的'right'和'top' position,但它不起作用。 不确定这是否是正确的方法。

有人可以建议如何将元素保存到新的 position 并从新的 position 进一步对其进行动画处理吗?

PS:如果您觉得还有其他更好的方法可以做到这一点,我也愿意接受建议/技术。

非常感谢提前!!

  1. 您可以使用fill选项使球获得最终的变换值,这与 css animation 中animation-fill-mode相同。

  2. 为了在执行下一个 animation 时不覆盖转换,您可以将 x 和 y 值保存为变量,并根据当前的xy state 执行任何 animation。 (从 x 到 x-60,而不是从 0 到 -60 等)

例子:

 /* Animation */ var item = document.getElementById('item'); var anim; var x=0, y=0; function myMoveLeft(){ anim=item.animate([ // keyframes { transform: `translate(${x}px, ${y}px)` }, { transform: `translate(${x-60}px, ${y}px)` } ], { duration: 1000, iterations: 1, fill: 'forwards' }); x -= 60; } function myMoveDown(){ anim=item.animate([ // keyframes { transform: `translate(${x}px, ${y}px)` }, { transform: `translate(${x}px, ${y+60}px)` } ], { duration: 1000, iterations: 1, fill: 'forwards' }); y += 60; // anim.onfinish(()=>{console.log("onfinish ran")}) } item.addEventListener('animationend', () => { console.log('Animation ended'); });
 button{ display:inline-block; height:40px; width:80px; } #myContainer { width: 400px; height: 400px; position: relative; background: lightgray; } #item { background: orange; position: absolute; right:30px; top:30px; height: 30px; width: 30px; border-radius:50%; }
 <p> <button onclick="myMoveLeft()">Left</button> <button onclick="myMoveDown()">Down</button> </p> <div id ="myContainer"> <div id="item"></div> </div>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM