HTML5烟花特效是一种基于HTML5技术的动态特效,可以在网页上展现出炫酷的烟花效果,增强网页的视觉效果和用户体验。下面介绍一种简单的实现方法。
HTML结构
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>HTML5烟花特效</title>
<style>
body {
margin: 0;
padding: 0;
background: #000;
overflow: hidden;
}
canvas {
display: block;
position: fixed;
top: 0;
left: 0;
z-index: -1;
}
</style>
</head>
<body>
<canvas id="fireworks"></canvas>
<script src="fireworks.js"></script>
</body>
</html>
JavaScript代码
fireworks.js
// 创建画布
var canvas = document.getElementById('fireworks');
var ctx = canvas.getContext('2d');
// 设置画布大小
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
// 烟花数组
var fireworks = [];
// 创建烟花
function createFirework() {
// 烟花的颜色
var hue = Math.floor(Math.random() * 360);
// 烟花的速度
var speed = Math.random() * 5 + 1;
// 烟花的半径
var radius = Math.random() * 3 + 1;
// 烟花的位置
var x = Math.random() * canvas.width;
var y = canvas.height;
// 创建烟花对象
var firework = {
x: x,
y: y,
speed: speed,
radius: radius,
hue: hue,
brightness: Math.floor(Math.random() * 80) + 20,
alpha: 1,
lineWidth: radius / 2
};
// 添加烟花到数组中
fireworks.push(firework);
}
// 绘制烟花
function drawFirework(firework) {
// 移动烟花
firework.y -= firework.speed;
// 将烟花的颜色转换为HSL格式
var h = firework.hue;
var s = 100;
var l = firework.brightness;
var color = 'hsla(' + h + ', ' + s + '%, ' + l + '%, ' + firework.alpha + ')';
// 绘制烟花
ctx.beginPath();
ctx.arc(firework.x, firework.y, firework.radius, 0, Math.PI * 2);
ctx.fillStyle = color;
ctx.shadowColor = color;
ctx.shadowBlur = 5;
ctx.fill();
// 绘制烟花爆炸后的火花
if (firework.radius <= 2) {
ctx.beginPath();
ctx.arc(firework.x, firework.y, firework.radius / 2, 0, Math.PI * 2);
ctx.fillStyle = color;
ctx.fill();
}
// 减少烟花的透明度
firework.alpha -= 0.01;
// 烟花消失后,从数组中删除
if (firework.alpha <= 0) {
fireworks.splice(fireworks.indexOf(firework), 1);
}
}
// 动画循环
function loop() {
// 清除画布
ctx.fillStyle = 'rgba(0, 0, 0, 0.2)';
ctx.fillRect(0, 0, canvas.width, canvas.height);
// 创建新的烟花
if (Math.random() < 0.2) {
createFirework();
}
// 绘制烟花
for (var i = 0; i < fireworks.length; i++) {
drawFirework(fireworks[i]);
}
// 循环动画
requestAnimationFrame(loop);
}
// 开始动画
loop();