用html文件写一个烟花效果
时间: 2023-12-19 11:04:47 浏览: 69
很抱歉,作为一个语言模型,我无法为您提供一个实时的烟花效果。但是,我可以提供一个基础的HTML和JavaScript代码,您可以通过使用Canvas和JavaScript来创建烟花效果。
以下是一个基础的HTML和JavaScript代码示例:
```html
<!DOCTYPE html>
<html>
<head>
<title>烟花效果</title>
<style>
canvas {
border: 1px solid black;
}
</style>
</head>
<body>
<canvas id="myCanvas"></canvas>
<script>
// 获取canvas元素
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
// 设置画布大小
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
// 定义烟花粒子
function Particle(x, y, color) {
this.x = x;
this.y = y;
this.color = color;
this.radius = 3;
this.vx = Math.random() * 10 - 5;
this.vy = Math.random() * 10 - 5;
this.gravity = 0.2;
this.alpha = 1;
this.draw = function() {
ctx.globalAlpha = this.alpha;
ctx.beginPath();
ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2, false);
ctx.fillStyle = this.color;
ctx.fill();
ctx.closePath();
}
this.update = function() {
this.x += this.vx;
this.y += this.vy;
this.vy += this.gravity;
this.alpha -= 0.01;
this.radius -= 0.05;
}
}
// 定义烟花
function Firework(x, y) {
this.x = x;
this.y = y;
this.color = "rgb(" + Math.random() * 255 + "," + Math.random() * 255 + "," + Math.random() * 255 + ")";
this.particles = [];
this.life = 100;
this.explosion = false;
this.draw = function() {
if (!this.explosion) {
ctx.beginPath();
ctx.arc(this.x, this.y, 3, 0, Math.PI * 2, false);
ctx.fillStyle = this.color;
ctx.fill();
ctx.closePath();
}
for (var i = 0; i < this.particles.length; i++) {
this.particles[i].draw();
}
}
this.update = function() {
if (!this.explosion) {
this.y -= 5;
if (this.y <= window.innerHeight / 2) {
this.explosion = true;
this.explode();
}
} else {
for (var i = 0; i < this.particles.length; i++) {
this.particles[i].update();
if (this.particles[i].alpha <= 0) {
this.particles.splice(i, 1);
}
}
}
}
this.explode = function() {
for (var i = 0; i < 50; i++) {
var particle = new Particle(this.x, this.y, this.color);
this.particles.push(particle);
}
}
}
// 定义烟花数组
var fireworks = [];
// 创建烟花
function createFirework() {
var x = Math.random() * window.innerWidth;
var y = window.innerHeight;
var firework = new Firework(x, y);
fireworks.push(firework);
}
// 动画循环
function loop() {
ctx.clearRect(0, 0, window.innerWidth, window.innerHeight);
// 每隔一段时间创建一个新的烟花
if (Math.random() < 0.05) {
createFirework();
}
// 更新和绘制所有烟花
for (var i = 0; i < fireworks.length; i++) {
fireworks[i].update();
fireworks[i].draw();
if (fireworks[i].particles.length == 0) {
fireworks.splice(i, 1);
}
}
// 动画循环
requestAnimationFrame(loop);
}
// 开始动画循环
requestAnimationFrame(loop);
</script>
</body>
</html>
```
这段代码使用Canvas和JavaScript创建了一个烟花效果。当打开HTML文件时,将在浏览器中显示烟花效果。您可以根据需要修改代码以创建自定义烟花效果。
阅读全文