文章目录
svg 烟花效果
以下是一个使用SVG(Scalable Vector Graphics)来实现烟花效果的示例代码。SVG是一种基于XML的矢量图形格式,适合用于创建各种图形和动画效果,包括烟花效果。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>SVG Fireworks</title>
<style>
svg {
background-color: black;
width: 800px;
height: 600px;
display: block;
margin: 0 auto;
}
</style>
</head>
<body>
<svg id="svg-fireworks" viewBox="0 0 800 600"></svg>
<script>
// 获取SVG元素
const svg = document.getElementById('svg-fireworks');
// 烟花粒子对象构造函数
function FireworkParticle(x, y, color) {
this.x = x;
this.y = y;
this.color = color;
this.vx = Math.random() * 6 - 3;
this.vy = Math.random() * -10 - 5;
this.radius = Math.random() * 3 + 1;
this.alpha = 1;
this.lifespan = 200;
}
// 更新烟花粒子的状态
FireworkParticle.prototype.update = function () {
this.x += this.vx;
this.y += this.vy;
this.vy += 0.1;
this.alpha -= 1 / this.lifespan;
};
// 绘制烟花粒子
FireworkParticle.prototype.draw = function () {
const circle = document.createElementNS('http://www.w3.org/2000/svg', 'circle');
circle.setAttribute('cx', this.x);
circle.setAttribute('cy', this.y);
circle.setAttribute('r', this.radius);
circle.setAttribute('fill', this.color);
circle.setAttribute('opacity', this.alpha);
svg.appendChild(circle);
};
// 烟花对象构造函数
function Firework(x, y) {
this.x = x;
this.y = y;
this.particles = [];
this.exploded = false;
this.color = `rgb(${
Math.random() * 255}, ${
Math.random() * 255}, ${
Math.random() * 255})`;
// 创建烟花的初始粒子
for (