vue中实现canvas动画
Vue 中实现 Canvas 动画的方法
使用 Vue 的 ref 和生命周期钩子
在 Vue 组件的模板中添加一个 canvas 元素,并通过 ref 获取其 DOM 引用。在 mounted 生命周期钩子中初始化 Canvas 并开始动画。

<template>
<canvas ref="canvas" width="400" height="400"></canvas>
</template>
<script>
export default {
mounted() {
const canvas = this.$refs.canvas;
const ctx = canvas.getContext('2d');
let x = 0;
function animate() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillRect(x, 50, 50, 50);
x += 1;
requestAnimationFrame(animate);
}
animate();
}
};
</script>
使用 Vue 的 watch 监听数据变化驱动动画
通过 Vue 的响应式数据驱动 Canvas 动画。当数据变化时,触发 Canvas 重绘。

<template>
<canvas ref="canvas" width="400" height="400"></canvas>
<button @click="updatePosition">移动方块</button>
</template>
<script>
export default {
data() {
return {
x: 0
};
},
mounted() {
this.draw();
},
methods: {
draw() {
const canvas = this.$refs.canvas;
const ctx = canvas.getContext('2d');
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillRect(this.x, 50, 50, 50);
},
updatePosition() {
this.x += 10;
}
},
watch: {
x() {
this.draw();
}
}
};
</script>
使用第三方库(如 p5.js)
结合第三方 Canvas 动画库(如 p5.js)可以简化复杂动画的实现。
<template>
<div ref="p5Canvas"></div>
</template>
<script>
import p5 from 'p5';
export default {
mounted() {
new p5((p) => {
let x = 0;
p.setup = () => {
p.createCanvas(400, 400);
};
p.draw = () => {
p.background(220);
p.rect(x, 50, 50, 50);
x += 1;
};
}, this.$refs.p5Canvas);
}
};
</script>
使用 vue-konva 库
如果需要更高级的 Canvas 功能,可以使用 vue-konva(基于 Konva 的 Vue 封装)。
<template>
<v-stage ref="stage" :config="stageConfig">
<v-layer>
<v-rect :config="rectConfig"></v-rect>
</v-layer>
</v-stage>
</template>
<script>
import { Vue } from 'vue-konva';
export default {
data() {
return {
stageConfig: {
width: 400,
height: 400
},
rectConfig: {
x: 0,
y: 50,
width: 50,
height: 50,
fill: 'red'
}
};
},
mounted() {
setInterval(() => {
this.rectConfig.x += 1;
}, 16);
}
};
</script>
优化 Canvas 动画性能
- 使用
requestAnimationFrame替代setInterval或setTimeout,确保动画流畅。 - 避免频繁的 Canvas 状态切换(如
fillStyle或strokeStyle的重复设置)。 - 对于静态背景,可以将其绘制到离屏 Canvas 中,减少重复绘制开销。
function animate() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
// 绘制逻辑
requestAnimationFrame(animate);
}
animate();
注意事项
- Canvas 是即时绘制的,每次更新需要手动清除并重绘所有内容。
- 在 Vue 中操作 Canvas 时,确保通过
ref获取 DOM 引用,而不是直接操作 DOM。 - 对于复杂动画,考虑使用 WebGL 或第三方库(如
Three.js)提升性能。






