vue中实现canvas动画
在 Vue 中实现 Canvas 动画
创建 Canvas 元素
在 Vue 组件的模板中直接添加 <canvas> 元素,并为其设置 ref 以便在 JavaScript 中访问:
<template>
<canvas ref="canvas" width="500" height="300"></canvas>
</template>
初始化 Canvas 上下文
在 mounted 生命周期钩子中获取 Canvas 上下文,并开始动画:
export default {
mounted() {
const canvas = this.$refs.canvas;
const ctx = canvas.getContext('2d');
this.animate(ctx);
},
methods: {
animate(ctx) {
// 动画逻辑
}
}
};
实现动画循环
使用 requestAnimationFrame 创建动画循环,确保动画平滑运行:
animate(ctx) {
let x = 0;
const draw = () => {
ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
ctx.fillStyle = 'blue';
ctx.fillRect(x, 50, 50, 50);
x += 1;
if (x > ctx.canvas.width) x = 0;
requestAnimationFrame(draw);
};
draw();
}
优化性能
在组件销毁时取消动画循环,避免内存泄漏:
export default {
data() {
return {
animationId: null
};
},
mounted() {
const ctx = this.$refs.canvas.getContext('2d');
this.animate(ctx);
},
methods: {
animate(ctx) {
const draw = () => {
// 动画逻辑
this.animationId = requestAnimationFrame(draw);
};
draw();
}
},
beforeDestroy() {
cancelAnimationFrame(this.animationId);
}
};
响应式调整
监听窗口大小变化并调整 Canvas 尺寸:
mounted() {
this.initCanvas();
window.addEventListener('resize', this.handleResize);
},
beforeDestroy() {
window.removeEventListener('resize', this.handleResize);
},
methods: {
handleResize() {
const canvas = this.$refs.canvas;
canvas.width = canvas.clientWidth;
canvas.height = canvas.clientHeight;
}
}
复杂动画示例
实现一个粒子系统动画:
animate(ctx) {
const particles = Array(100).fill().map(() => ({
x: Math.random() * ctx.canvas.width,
y: Math.random() * ctx.canvas.height,
size: Math.random() * 5 + 1,
speedX: Math.random() * 2 - 1,
speedY: Math.random() * 2 - 1
}));
const draw = () => {
ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
particles.forEach(p => {
p.x += p.speedX;
p.y += p.speedY;
if (p.x < 0 || p.x > ctx.canvas.width) p.speedX *= -1;
if (p.y < 0 || p.y > ctx.canvas.height) p.speedY *= -1;
ctx.fillStyle = `rgba(100, 150, 255, ${p.size/6})`;
ctx.beginPath();
ctx.arc(p.x, p.y, p.size, 0, Math.PI * 2);
ctx.fill();
});
this.animationId = requestAnimationFrame(draw);
};
draw();
}
使用第三方库
对于复杂动画,可以考虑使用专门的 Canvas 库如:
p5.js:适合创意编码fabric.js:提供高级对象模型konva.js:专注于交互式图形
通过以上方法,可以在 Vue 应用中高效地实现各种 Canvas 动画效果。







