Skip to content

requestAnimationFrame 动画


loading
  • requestAnimationFrame
    • 回调函数接收一个参数 timestamp,表示当前时间戳(以毫秒为单位),可以用于计算动画的进度。
javascript
function animate(timestamp) {
  // 动画逻辑
  requestAnimationFrame(animate)
}
requestAnimationFrame(animate)
vue
<template>
  <div>
    <canvas ref="canvas" width="400" height="200" style="border: 1px solid #000;"></canvas>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'

const canvas = ref(null)
// let intervalId = null; // 用于存储 setInterval 的 ID
let animationFrameId = null // 用于存储 requestAnimationFrame 的 ID
let x = 0 // 方块的初始位置
const speed = 2 // 方块移动的速度

const animate = () => {
  const ctx = canvas.value.getContext('2d')
  ctx.clearRect(0, 0, canvas.value.width, canvas.value.height) // 清空画布

  // 绘制方块
  ctx.fillStyle = 'blue'
  ctx.fillRect(x, 50, 50, 50) // 在 (x, 50) 位置绘制一个 50x50 的方块

  x += speed // 更新方块的位置

  // 如果方块超出画布边界,则重置位置
  if (x > canvas.value.width) {
    x = -50 // 从左侧重新开始
  }

  animationFrameId = requestAnimationFrame(animate) // 请求下一帧动画
}

onMounted(() => {
  // intervalId = setInterval(animate, 16); // 每 16 毫秒调用一次 animate 函数
  animate() // 启动动画
})

onUnmounted(() => {
  // clearInterval(intervalId); // 组件卸载时清除定时器
  cancelAnimationFrame(animationFrameId) // 组件卸载时取消动画
})
</script>

<style scoped></style>

Released under the MIT License.