canvas 礼花特效 vue3
时间: 2025-01-18 15:19:11 浏览: 47
### 如何在 Vue3 中使用 Canvas 实现礼花特效
#### 创建 Vue 组件并引入 Canvas
为了实现在 Vue3 项目中的 Canvas 礼花特效,可以创建一个新的组件 `Fireworks.vue` 来专门处理这个功能。在这个组件里,通过 `<canvas>` 元素来绘制动画效果。
```html
<template>
<div class="firework-container">
<canvas ref="fireworkCanvas"></canvas>
</div>
</template>
<script setup>
import { onMounted, ref } from 'vue'
const fireworkCanvas = ref(null)
onMounted(() => {
const canvas = fireworkCanvas.value
const ctx = canvas.getContext('2d')
// 设置画布大小跟随窗口变化
function resizeCanvas() {
canvas.width = window.innerWidth
canvas.height = window.innerHeight
}
window.addEventListener('resize', resizeCanvas)
resizeCanvas()
// 定义烟花类和其他逻辑...
})
</script>
<style scoped>
.firework-container {
position: absolute;
top: 0;
left: 0;
z-index: -1; /* 确保不会覆盖其他页面元素 */
}
</style>
```
#### 编写烟花粒子系统的核心算法
接下来,在上述脚本部分继续定义烟花爆炸的效果模拟函数:
```javascript
class Particle {
constructor(x, y) {
this.x = x
this.y = y
this.color = getRandomColor()
this.size = Math.random() * 5 + 2
this.velocityX = (Math.random() - 0.5) * 10
this.velocityY = (Math.random() - 0.5) * 10
this.gravity = 0.1
this.friction = 0.97
}
update() {
this.velocityY += this.gravity
this.x += this.velocityX
this.y += this.velocityY
this.velocityX *= this.friction
this.velocityY *= this.friction
}
draw(ctx) {
ctx.fillStyle = this.color
ctx.beginPath()
ctx.arc(this.x, this.y, this.size, 0, Math.PI * 2)
ctx.fill()
}
}
function createExplosion(x, y) {
let particles = []
for(let i=0;i<100;i++){
particles.push(new Particle(x,y))
}
return particles
}
// 颜色随机生成辅助方法
function getRandomColor() {
const colors = ['#ff6b6b','#feca57','#4ecdc4','#aabbcc']
return colors[Math.floor(Math.random()*colors.length)]
}
```
这部分代码实现了基本的粒子物理行为以及颜色的选择机制[^1]。
#### 动态渲染与事件触发
为了让用户交互能够触发展示烟花效果,可以在鼠标点击或移动时调用 `createExplosion()` 函数,并将产生的粒子加入到全局数组中定期更新它们的位置和状态。
```javascript
let allParticles = []
function animate() {
requestAnimationFrame(animate)
ctx.clearRect(0, 0, canvas.width, canvas.height)
if(allParticles.length > 0){
allParticles.forEach((particle,index)=>{
particle.update()
particle.draw(ctx)
// 当粒子变得太小时移除它
if(particle.size<=0.5 || !isParticleVisible(particle)){
allParticles.splice(index,1)
}
})
}
}
canvas.addEventListener('click',(event)=>{
const mouseX=event.clientX,
mouseY=event.clientY
allParticles=[...allParticles,...createExplosion(mouseX,mouseY)]
})
animate()
```
这段代码展示了如何监听用户的点击动作并在指定位置产生活动的烟花效果。
阅读全文
相关推荐














