how to move a (basket)ball across the screen with delay?

53 Views Asked by At

I have an image of a ball that I wish to move using JS. I will add more precise code later for .left and .top that will precisely describe the throw of the ball with gravity function. What I have now goes too fast to see.

I have:

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";
    
    } 

This works, but it goes too fast to see the movement. How would I make this into a visible animation?

thanks!

1

There are 1 best solutions below

5
noname On

You can make a game loop using requestAnimationFrame and 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">

Or, even better, use CSS.

You can use CSS animations to move the ball without 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">