4. 结合 cancelAnimationFrame
requestAnimationFrame
在调用时会返回一个唯一的标识符,这个标识符是一个整数,代表了请求的帧的ID。这个ID可以用来取消尚未执行的帧请求,通过调用 cancelAnimationFrame
并将该ID作为参数传入。
下面是一个使用 requestAnimationFrame
和 cancelAnimationFrame
的例子,演示了如何在用户点击按钮时开始动画,并在再次点击时停止动画:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Animation Control with requestAnimationFrame and cancelAnimationFrame</title>
<style>
#animationBox {
width: 100px;
height: 100px;
background-color: red;
position: absolute;
left: 0;
top: 0;
}
</style>
</head>
<body>
<div id="animationBox"></div>
<button id="toggleAnimation">Toggle Animation</button>
<script>
const animationBox = document.getElementById('animationBox');
const toggleButton = document.getElementById('toggleAnimation');
let requestId;
let isAnimating = false;
function animate() {
if (!isAnimating) return;
// 移动动画盒
const currentLeft = parseInt(window.getComputedStyle(animationBox).left);
animationBox.style.left = `${currentLeft + 1}px`;
// 如果动画盒到达了右边界,反转方向
if (parseInt(window.getComputedStyle(animationBox).left) >= window.innerWidth - 100) {
animationBox.style.left = `${window.innerWidth - 100}px`;
}
// 请求下一帧
requestId = requestAnimationFrame(animate);
}
toggleButton.addEventListener('click', () => {
if (isAnimating) {
// 停止动画
cancelAnimationFrame(requestId);
isAnimating = false;
toggleButton.textContent = "Start Animation";
} else {
// 开始动画
requestId = requestAnimationFrame(animate);
isAnimating = true;
toggleButton.textContent = "Stop Animation";
}
});
</script>
</body>
</html>
在这个例子中:
我们有一个红色的方块 (
animationBox
),初始位置在屏幕左上角。用户可以通过点击按钮 (
toggleButton
) 来开始或停止动画。当动画开始时,
animate
函数会被调用,它会不断地将方块向右移动。当方块到达屏幕的右边界时,动画会停止移动方块。
requestId
变量存储了requestAnimationFrame
返回的ID,以便在需要时取消动画。当用户点击按钮时,如果动画正在进行 (
isAnimating
为true
),则调用cancelAnimationFrame(requestId)
来取消动画;如果动画未进行,则开始动画。这种控制机制使得在用户交互或特定条件满足时动态控制动画成为可能。
通过本教程,你不仅学习了
requestAnimationFrame
的基本原理和使用方法,还通过实战案例掌握了如何利用它来创建平滑的动画效果。合理使用requestAnimationFrame
和cancelAnimationFrame
可以显著提升Web应用的性能和用户体验。
效果如下: