JavaScript - DOM 動畫
Hello, future web developers! Today, we're going to embark on an exciting journey into the world of JavaScript DOM animation. As your friendly neighborhood computer science teacher, I'm thrilled to guide you through this fascinating topic. Trust me, by the end of this lesson, you'll be making web pages come alive with motion!
使用 JavaScript 動畫化 DOM 元素
Before we dive into the nitty-gritty of animation, let's quickly recap what the DOM is. DOM stands for Document Object Model, and it's essentially a programming interface for HTML documents. It represents the structure of a document as a tree-like hierarchy, allowing us to manipulate web page content and structure using JavaScript.
Now, when we talk about animating DOM elements, we're referring to changing their properties over time to create the illusion of movement or transformation. It's like creating a flip book animation, but with code!
Let's start with a simple example:
<div id="myBox" style="width: 100px; height: 100px; background-color: red; position: absolute;"></div>
<script>
let box = document.getElementById('myBox');
let position = 0;
function moveBox() {
position += 1;
box.style.left = position + 'px';
}
setInterval(moveBox, 10);
</script>
In this example, we're moving a red box across the screen. Let's break it down:
- We create a
<div>
element with some initial styles. - We use
document.getElementById('myBox')
to get a reference to our box. - We define a
moveBox()
function that increments theposition
and updates theleft
style property of the box. - We use
setInterval()
to callmoveBox()
every 10 milliseconds, creating a smooth animation.
使用 setInterval() 方法動畫化 DOM 元素
The setInterval()
method is one way to create animations in JavaScript. It repeatedly calls a function at specified intervals. Here's a more complex example:
<div id="bouncer" style="width: 50px; height: 50px; background-color: blue; border-radius: 25px; position: absolute;"></div>
<script>
let bouncer = document.getElementById('bouncer');
let x = 0;
let y = 0;
let dx = 2;
let dy = 2;
function animate() {
x += dx;
y += dy;
if (x > window.innerWidth - 50 || x < 0) dx = -dx;
if (y > window.innerHeight - 50 || y < 0) dy = -dy;
bouncer.style.left = x + 'px';
bouncer.style.top = y + 'px';
}
setInterval(animate, 10);
</script>
This script creates a bouncing ball effect:
- We set up initial positions (
x
,y
) and velocities (dx
,dy
). - In the
animate()
function, we update the position based on the velocity. - We check if the ball hits the edges of the window and reverse its direction if it does.
- We update the ball's position on the screen.
-
setInterval()
callsanimate()
every 10ms, creating smooth motion.
使用 requestAnimationFrame() 方法動畫化 DOM 元素
While setInterval()
works, modern browsers offer a more efficient method: requestAnimationFrame()
. This method tells the browser that you wish to perform an animation and requests that the browser calls a specified function to update an animation before the next repaint.
Let's rewrite our bouncing ball using requestAnimationFrame()
:
<div id="bouncer" style="width: 50px; height: 50px; background-color: green; border-radius: 25px; position: absolute;"></div>
<script>
let bouncer = document.getElementById('bouncer');
let x = 0;
let y = 0;
let dx = 2;
let dy = 2;
function animate() {
x += dx;
y += dy;
if (x > window.innerWidth - 50 || x < 0) dx = -dx;
if (y > window.innerHeight - 50 || y < 0) dy = -dy;
bouncer.style.left = x + 'px';
bouncer.style.top = y + 'px';
requestAnimationFrame(animate);
}
requestAnimationFrame(animate);
</script>
The main difference here is that instead of using setInterval()
, we're calling requestAnimationFrame(animate)
at the end of our animate()
function. This creates a loop where the browser calls animate()
just before each repaint.
通過更改 CSS 屬性來動畫化 DOM 元素
So far, we've been changing CSS properties directly using JavaScript. However, modern web development often leverages CSS transitions and animations for smoother performance. Let's see how we can trigger CSS animations using JavaScript:
<style>
.box {
width: 100px;
height: 100px;
background-color: purple;
position: absolute;
transition: all 0.5s ease;
}
</style>
<div id="myBox" class="box"></div>
<script>
let box = document.getElementById('myBox');
let position = 0;
function moveBox() {
position += 50;
box.style.transform = `translateX(${position}px)`;
if (position < 200) {
requestAnimationFrame(moveBox);
}
}
box.addEventListener('click', function() {
position = 0;
requestAnimationFrame(moveBox);
});
</script>
In this example:
- We define a CSS class with a transition property.
- Our JavaScript function changes the
transform
property instead ofleft
. - We use
requestAnimationFrame()
to create a smooth animation. - The animation starts when the box is clicked.
This method often results in smoother animations because the browser can optimize CSS transitions.
Here's a table summarizing the methods we've discussed:
方法 | 優點 | 缺點 |
---|---|---|
setInterval() |
Simple to understand and implement | Can be less efficient, may cause jank |
requestAnimationFrame() |
More efficient, syncs with browser's refresh rate | Slightly more complex to implement |
CSS Transitions | Very smooth, can be hardware accelerated | Limited control over animation steps |
Remember, animation can greatly enhance user experience, but it should be used judiciously. Too much animation can be distracting or even cause motion sickness for some users.
That's it for our journey into JavaScript DOM animation! I hope you've enjoyed this lesson as much as I've enjoyed teaching it. Keep practicing, keep animating, and most importantly, keep having fun with code!
Credits: Image by storyset