html css js实现一个绽放烟花的代码
时间: 2023-06-13 09:07:54 浏览: 116
跨年烟花代码(HTML+CSS+JS)
以下是一个简单的HTML、CSS、JavaScript实现绽放烟花的代码:
HTML代码:
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>绽放烟花</title>
<style>
body {
background-color: #111;
margin: 0;
padding: 0;
overflow: hidden;
cursor: none;
}
canvas {
display: block;
}
</style>
</head>
<body>
<canvas></canvas>
<script src="fireworks.js"></script>
</body>
</html>
```
CSS代码:
```css
body {
background-color: #111;
margin: 0;
padding: 0;
overflow: hidden;
cursor: none;
}
canvas {
display: block;
}
```
JavaScript代码(保存为fireworks.js文件):
```javascript
var canvas = document.querySelector("canvas");
var c = canvas.getContext("2d");
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
var gravity = 0.2;
var friction = 0.98;
function randomColor() {
return (
"rgba(" +
Math.round(Math.random() * 255) +
"," +
Math.round(Math.random() * 255) +
"," +
Math.round(Math.random() * 255) +
"," +
Math.round(Math.random() * 10) / 10 +
")"
);
}
function Particle(x, y, radius, color, velocity) {
this.x = x;
this.y = y;
this.radius = radius;
this.color = color;
this.velocity = velocity;
this.alpha = 1;
this.draw = function () {
c.save();
c.globalAlpha = this.alpha;
c.beginPath();
c.arc(this.x, this.y, this.radius, 0, Math.PI * 2, false);
c.fillStyle = this.color;
c.fill();
c.restore();
};
this.update = function () {
this.draw();
this.velocity.y += gravity;
this.x += this.velocity.x;
this.y += this.velocity.y;
this.alpha -= 0.01;
};
}
function Firework(x, y) {
this.x = x;
this.y = y;
this.particles = [];
this.color = randomColor();
this.velocity = {
x: Math.random() * 6 - 3,
y: Math.random() * 3 + 3,
};
this.explode = function () {
for (var i = 0; i < 50; i++) {
var particle = new Particle(
this.x,
this.y,
Math.random() * 2,
this.color,
{
x: (Math.random() - 0.5) * (Math.random() * 6),
y: (Math.random() - 0.5) * (Math.random() * 6),
}
);
this.particles.push(particle);
}
};
this.draw = function () {
c.save();
c.beginPath();
c.arc(this.x, this.y, 3, 0, Math.PI * 2, false);
c.fillStyle = this.color;
c.fill();
c.restore();
};
this.update = function () {
this.draw();
if (this.velocity.y >= 0) {
this.explode();
fireworks.splice(fireworks.indexOf(this), 1);
}
this.velocity.y += gravity;
this.x += this.velocity.x;
this.y += this.velocity.y;
};
}
var fireworks = [];
function animate() {
requestAnimationFrame(animate);
c.fillStyle = "rgba(0,0,0,0.2)";
c.fillRect(0, 0, canvas.width, canvas.height);
if (Math.random() < 0.05) {
var firework = new Firework(Math.random() * canvas.width, canvas.height);
fireworks.push(firework);
}
for (var i = 0; i < fireworks.length; i++) {
fireworks[i].update();
}
}
animate();
```
打开HTML文件,即可看到绽放烟花效果。
阅读全文