How is the spider bouncing around the screen?
What this simple code does:
- Creates a little black circle (
#spider). - Moves it by adding velocity to
xandyeach frame. - Reverses velocity when it hits a wall → bouncing effect.
- Runs smoothly using
requestAnimationFrame.
1. The browser has a built-in animation loop
Browsers try to draw the screen about 60 times per second (60 FPS).
requestAnimationFrame() lets you say:
“Please run this function right before the browser draws the next frame.”
So it syncs your code with the screen refresh.
2. You give requestAnimationFrame() a function
requestAnimationFrame(animate);
3. The animate() function calls requestAnimationFrame again
function animate() {
// move the spider
// bounce it off walls
requestAnimationFrame(animate);
}
This is crucial.
Every time animate() runs, it asks the browser to run it again on the next frame.
That creates an endless loop:
4. Why not use setInterval instead?
You could animate using:
setInterval(animate, 16); // ~60fps
BUT:
requestAnimationFrameis smoother,- it pauses automatically when the tab is hidden (saves battery),
- it syncs to the monitor’s refresh rate,
- it’s the standard for modern animations.
5. In the code…
This line:
requestAnimationFrame(animate);
means:
“Run animate() again at the next frame so the spider keeps moving.”
Without it, the spider would move once and stop.
HTML
<div id="spider"></div>
CSS
body {
margin: 0;
overflow: hidden;
}
/* tiny spider */
#spider {
width: 40px;
height: 40px;
background: black;
border-radius: 50%;
position: fixed;
}
Javascript
const spider = document.getElementById("spider");
// starting position
let x = 100;
let y = 100;
// velocity (px per frame)
let vx = 6;
let vy = 4;
function animate() {
x += vx;
y += vy;
// bounce off left/right edges
if (x <= 0 || x + spider.offsetWidth >= window.innerWidth) {
vx = -vx;
}
// bounce off top/bottom edges
if (y <= 0 || y + spider.offsetHeight >= window.innerHeight) {
vy = -vy;
}
// update position
spider.style.left = x + "px";
spider.style.top = y + "px";
requestAnimationFrame(animate);
}
animate();


Leave a Reply