Create animations using variables (position control)

20 Animation – Using Variables for Position Control

1️⃣ What is Animation?

Animation is the illusion of motion created by displaying a sequence of images (frames) that change over time. Think of it like a flip‑book: each page shows the character a little further along in its journey. In web development we usually control animation with CSS or JavaScript, but today we’ll focus on variables to move objects smoothly.

2️⃣ Variables in Animation – The “Position Control” Toolkit

A variable is a named storage location that can hold a value which may change during the animation. In JavaScript we often use let or const to declare them, and in CSS we use -- custom properties. Variables let us:

  • Change the position of an element over time.
  • Make animations reusable by swapping variable values.
  • Keep code tidy – you can update one variable instead of editing many lines.

3️⃣ Example: Moving a Ball Across the Screen 🏀

Below is a simple JavaScript example that moves a ball horizontally using a variable called positionX. The ball’s left style property is updated every 20 ms.

let positionX = 0; // starting position in pixels
const ball = document.getElementById('ball');

function animate() {
  positionX += 5; // move 5px each frame
  ball.style.left = positionX + 'px';
  if (positionX < window.innerWidth) {
    requestAnimationFrame(animate);
  }
}
animate();

Here’s what’s happening:

  1. We start at positionX = 0 (the left edge).
  2. Each frame we add 5 to positionX, so the ball moves right.
  3. We set the ball’s left CSS property to the new value.
  4. When the ball reaches the screen’s right edge, the animation stops.

4️⃣ Practice Exercise: Create a Bouncing Ball 🎯

Your task: modify the code above so that the ball bounces back and forth between the left and right edges of the screen. Hint: use a second variable direction that is either 1 (right) or -1 (left). When the ball hits an edge, flip the direction.

5️⃣ Summary Table of Key Concepts 📊

Concept What It Does Example Syntax
Variable Declaration Stores a value that can change. let positionX = 0;
Updating Position Adds a step to the variable each frame. positionX += 5;
Applying to CSS Sets the element’s style property. ball.style.left = positionX + 'px';
Looping Animation Uses requestAnimationFrame for smooth frames. requestAnimationFrame(animate);

6️⃣ Final Thought: The Puppet Analogy 🎭

Imagine you’re a puppeteer. Each string (variable) you pull changes the puppet’s position. By controlling the strings with precise timing, you create a dance. In coding, variables are those strings, and requestAnimationFrame is the rhythm that keeps the dance smooth. Keep experimenting – the more you pull, the more fluid your animations become!

Revision

Log in to practice.

0 views 0 suggestions