如何在屏幕上延迟移动(篮)球?

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

我有一个球的图像,我希望使用 JS 移动它。稍后我将为 .left 和 .top 添加更精确的代码,以精确描述具有重力函数的球的投掷。我现在所拥有的东西转得太快而看不到。

我有:

HTML

<img id="bal1" src="Afbeeldingen/bal1.png" alt="Bal" width="100" height="100">

JS

    for (var x = 0; x < 10; x++) {
      document.getElementById('bal1').style.left=30*x +"px";
      document.getElementById('bal1').style.top=30*x +"px";
    
    } 

这可行,但速度太快,看不到运动。我如何将其制作成可见的动画?

谢谢!

javascript animation wait
1个回答
0
投票

您可以使用

requestAnimationFrame
Date.now()
制作游戏循环。

const speed = 0.1; // Set the ball speed

const ball = document.getElementById("ball1") // Find the ball
let startTime = Date.now();

function tick() {
  const time = Date.now() - startTime; // miliseconds since game started
  
  // move the ball
  ball.style.left = time * speed + "px";
  ball.style.top = time * speed + "px";
  
  // Stop after 300 pixels traveled
  const traveled = ball.style.left.slice(0, -2); // The ball's position has "px" at the end, so this line of code removes it.
  if (traveled > 300) return; // Return early instead of calling the next frame
  
  // call tick next frame
  window.requestAnimationFrame(tick);
}

// Start the game
tick();
#ball1 {
  position: absolute;
}
<img id="ball1" src="https://target.scene7.com/is/image/Target/GUEST_20affc7e-e0d7-4eb6-a6f3-68d13520f8be?wid=488&hei=488&fmt=pjpeg" alt="Ball" width="100" height="100">

或者,更好的是,使用 CSS。

您可以使用CSS动画来移动球无需Javascript。

/* Create the animation */
@keyframes ballAnimation {
  from { /* The ball starts... */
    top: 0px;
    left: 0px;
  }
  to { /* And ends up... */
    top: 300px;
    left: 300px;
  }
}

#ball1 {
  /* Set the ball's position to absolute*/
  position: absolute;
  
  /* Give the animation to the ball */
  animation-name: ballAnimation;
  animation-duration: 3s; // s stands for seconds
}
<img id="ball1" src="https://target.scene7.com/is/image/Target/GUEST_20affc7e-e0d7-4eb6-a6f3-68d13520f8be?wid=488&hei=488&fmt=pjpeg" alt="Ball" width="100" height="100">

© www.soinside.com 2019 - 2024. All rights reserved.