用html写一段烟花绽放的代码
时间: 2023-02-07 22:07:12 浏览: 234
烟火代码(js)html放烟花代码
<!DOCTYPE html>
<html>
<head>
<style>
#container {
width: 100%;
height: 100%;
position: fixed;
top: 0;
left: 0;
z-index: -1;
}
#canvas {
width: 100%;
height: 100%;
}
</style>
</head>
<body>
<div id="container">
<canvas id="canvas"></canvas>
</div>
<script>
// Set up canvas
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var W = window.innerWidth;
var H = window.innerHeight;
canvas.width = W;
canvas.height = H;
// Create particles
var particles = [];
for (var i = 0; i < 50; i++) {
particles.push(new create_particle());
}
function create_particle() {
// Initial position
this.x = Math.random() * W;
this.y = Math.random() * H;
// Random velocity
this.vx = Math.random() * 20 - 10;
this.vy = Math.random() * 20 - 10;
// Random color
var r = Math.floor(Math.random() * 255);
var g = Math.floor(Math.random() * 255);
var b = Math.floor(Math.random() * 255);
this.color = "rgba(" + r + "," + g + "," + b + ", 0.5)";
// Random size
this.radius = Math.random() * 20 + 20;
}
// Draw particles
function draw() {
ctx.clearRect(0, 0, W, H);
for (var i = 0; i < particles.length; i++) {
var p = particles[i];
ctx.beginPath();
ctx.fillStyle = p.color;
ctx.arc(p.x, p.y, p.radius, 0, Math.PI * 2, true);
ctx.fill();
}
update();
}
// Update particles
function update() {
for (var i = 0; i < particles.length; i++) {
var p = particles[i];
// Change velocity
p.x += p.vx;
p.y += p.vy;
// Bounce off edges
if (p.x + p.radius > W) {
p.x = p.radius;
p.vx = -p.vx;
}
if (p.x - p.radius < 0) {
p.x = W - p.radius;
p.vx = -p.vx;
}
if (p.y + p.radius > H) {
p.y = p.radius;
p.vy = -p.vy;
}
if (p.y - p.radius < 0) {
p.y = H - p.radius;
p.vy = -p.vy;
}
阅读全文