如何在JavaScript中保存动画后的对象位置?

问题描述 投票:1回答:1

我正在尝试为一个游戏设置动画对象,在该游戏中,应该在按下用户按钮时使球向上,向右,向左和向下移动。我试图通过在球上使用.animate()函数来实现这一目标。但是在每个动画事件之后,球都会重置到其初始位置,并且不会继续从其“新”位置移动。有什么办法可以做到这一点?

为简化起见,以下是我的压缩代码段:

/* 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()和Event Listener'animationend',希望我可以更新新的'right'和'top'位置,但是不起作用。不知道这是否是正确的方法。

有人可以建议如何将元素保存到新位置并从该新位置对其进行动画处理吗?

PS:如果您认为还有其他更好的方法,也可以接受建议/技术。

非常感谢!

javascript html css css-animations css-transforms
1个回答
0
投票
  1. 您可以使用fill选项使球获得最终的变换值,该选项与CSS动画中的animation-fill-mode相同。

  2. 为了在执行下一个动画时不覆盖变换,可以将x和y值另存为变量,并根据当前xy状态进行任何动画处理。 (从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>
© www.soinside.com 2019 - 2024. All rights reserved.