以下是一个简单的带字烟花效果的前端页面代码:

HTML部分:

<div class='fireworks-container'>
  <h1 class='fireworks-text'>Happy New Year!</h1>
  <canvas class='fireworks-canvas'></canvas>
</div>

CSS部分:

.fireworks-container {
  position: relative;
  width: 100%;
  height: 100vh;
  background-color: #000;
}

.fireworks-text {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  color: #fff;
  font-size: 5rem;
  z-index: 1;
}

.fireworks-canvas {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 0;
}

JavaScript部分:

// 获取画布和上下文
const canvas = document.querySelector('.fireworks-canvas')
const ctx = canvas.getContext('2d')

// 画布大小
canvas.width = window.innerWidth
canvas.height = window.innerHeight

// 鼠标位置
let mouse = {
  x: null,
  y: null,
}

// 监听鼠标移动事件
window.addEventListener('mousemove', (e) => {
  mouse.x = e.x
  mouse.y = e.y
})

// 创建烟花粒子类
class FireworkParticle {
  constructor(x, y, color) {
    this.x = x
    this.y = y
    this.color = color
    this.radius = 3

    // 随机速度和方向
    this.velocity = {
      x: Math.random() * 6 - 3,
      y: Math.random() * 6 - 3,
    }

    // 加速度
    this.gravity = 0.1
    this.friction = 0.97

    // 记录时间
    this.timeToLive = 100
    this.startTime = Date.now()
  }

  // 更新粒子状态
  update() {
    this.x += this.velocity.x
    this.y += this.velocity.y
    this.velocity.y += this.gravity
    this.velocity.x *= this.friction
    this.velocity.y *= this.friction
    this.timeToLive = 100 - (Date.now() - this.startTime)
  }

  // 绘制粒子
  draw() {
    ctx.beginPath()
    ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2, false)
    ctx.fillStyle = this.color
    ctx.fill()
  }

  // 爆炸
  explode() {
    for (let i = 0; i < 30; i++) {
      const particle = new FireworkParticle(
        this.x,
        this.y,
        `hsl(${Math.random() * 360}, 50%, 50%)`
      )
      particles.push(particle)
    }
  }
}

// 粒子数组
let particles = []

// 更新粒子状态和绘制
function animate() {
  requestAnimationFrame(animate)
  ctx.fillStyle = 'rgba(0, 0, 0, 0.2)'
  ctx.fillRect(0, 0, canvas.width, canvas.height)

  // 如果鼠标位置存在
  if (mouse.x !== null && mouse.y !== null) {
    // 创建一个新的烟花
    const firework = new FireworkParticle(mouse.x, mouse.y, '#fff')
    particles.push(firework)

    // 重置鼠标位置
    mouse.x = null
    mouse.y = null
  }

  // 更新和绘制所有粒子
  particles.forEach((particle, index) => {
    if (particle.timeToLive > 0) {
      particle.update()
      particle.draw()
    } else {
      particle.explode()
      particles.splice(index, 1)
    }
  })
}

animate()

效果如图所示:

带字烟花效果

HTML CSS JavaScript 实现带字烟花效果

原文地址: https://www.cveoy.top/t/topic/nVGA 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录