HTML5夜空烟花制作入门教程,轻松学会用代码打造炫酷星空效果

2026-06-18 0 阅读

在这个数字化时代,用代码创造美丽的世界已经不再是梦想。今天,我们就来一起学习如何使用HTML5和JavaScript制作夜空烟花效果。这个过程既有趣又富有挑战性,让我们一起探索吧!

准备工作

在开始之前,你需要以下准备工作:

  1. HTML5文档:创建一个基本的HTML5文档。
  2. CSS样式:添加一些CSS样式来美化烟花效果。
  3. JavaScript代码:编写JavaScript来控制烟花的运动和爆炸效果。

HTML结构

首先,我们需要一个容器来展示烟花效果。在HTML文档中添加以下代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>HTML5夜空烟花效果</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <canvas id="fireworksCanvas"></canvas>
    <script src="script.js"></script>
</body>
</html>

CSS样式

接下来,我们需要添加一些CSS样式来美化烟花效果。在styles.css文件中添加以下代码:

body, html {
    margin: 0;
    padding: 0;
    width: 100%;
    height: 100%;
    overflow: hidden;
    background-color: #000;
}

#fireworksCanvas {
    width: 100%;
    height: 100%;
}

JavaScript代码

现在,我们来编写JavaScript代码来控制烟花的运动和爆炸效果。在script.js文件中添加以下代码:

// 获取画布和绘图上下文
const canvas = document.getElementById('fireworksCanvas');
const ctx = canvas.getContext('2d');

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

// 烟花类
class Firework {
    constructor(x, y, targetX, targetY, color) {
        this.x = x;
        this.y = y;
        this.targetX = targetX;
        this.targetY = targetY;
        this.color = color;
        this.velocity = {
            x: (targetX - x) / 10,
            y: (targetY - y) / 10
        };
        this.brightness = Math.random() * 70 + 30;
        this.alpha = 1;
        this.decay = Math.random() * 0.015 + 0.005;
    }

    update() {
        this.velocity.y += 0.1;
        this.x += this.velocity.x;
        this.y += this.velocity.y;
        this.alpha -= this.decay;
    }

    draw() {
        ctx.save();
        ctx.globalAlpha = this.alpha;
        ctx.beginPath();
        ctx.arc(this.x, this.y, 5, 0, Math.PI * 2, false);
        ctx.fillStyle = `hsl(${this.color}, 100%, ${this.brightness}%)`;
        ctx.fill();
        ctx.restore();
    }
}

// 创建烟花数组
const fireworks = [];

// 添加烟花到画布
function addFirework() {
    const x = Math.random() * canvas.width;
    const y = canvas.height;
    const targetX = Math.random() * canvas.width;
    const targetY = Math.random() * canvas.height / 2;
    const color = Math.random() * 360;
    fireworks.push(new Firework(x, y, targetX, targetY, color));
}

// 更新和绘制烟花
function loop() {
    requestAnimationFrame(loop);
    ctx.fillStyle = 'rgba(0, 0, 0, 0.1)';
    ctx.fillRect(0, 0, canvas.width, canvas.height);

    for (let i = fireworks.length - 1; i >= 0; i--) {
        fireworks[i].update();
        fireworks[i].draw();

        if (fireworks[i].alpha <= 0) {
            fireworks.splice(i, 1);
        }
    }

    if (Math.random() < 0.05) {
        addFirework();
    }
}

// 初始化
loop();

总结

通过以上步骤,你已经成功地制作了一个炫酷的夜空烟花效果。你可以根据自己的喜好调整烟花颜色、亮度、速度等参数,创造出独一无二的烟花效果。希望这个教程能帮助你更好地理解HTML5和JavaScript,继续探索更多有趣的创意吧!

分享到: