HTML5夜景放烟花绽放动画效果代码
时间: 2023-12-20 19:29:12 浏览: 273
以下是HTML5夜景放烟花绽放动画效果的代码,你可以将其复制到你的HTML文件中使用:
```html
<!DOCTYPE html>
<html>
<head>
<title>HTML5夜景放烟花绽放动画效果</title>
<style type="text/css">
canvas {
position: absolute;
top: 0;
left: 0;
z-index: -1;
}
</style>
</head>
<body>
<canvas id="canvas"></canvas>
<script type="text/javascript">
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var W = window.innerWidth;
var H = window.innerHeight;
canvas.width = W;
canvas.height = H;
var particles = [];
var mouse = {};
var particle_count = 100;
for(var i = 0; i < particle_count; i++) {
particles.push(new particle());
}
canvas.addEventListener('mousemove', track_mouse, false);
function track_mouse(e) {
mouse.x = e.pageX;
mouse.y = e.pageY;
}
function particle() {
this.speed = {x: -1 + Math.random() * 2, y: -5 + Math.random() * 5};
if(mouse.x && mouse.y) {
this.location = {x: mouse.x, y: mouse.y};
}
else {
this.location = {x: W/2, y: H/2};
}
this.radius = 10 + Math.random() * 20;
this.life = 20 + Math.random() * 10;
this.remaining_life = this.life;
this.r = Math.round(Math.random() * 255);
this.g = Math.round(Math.random() * 255);
this.b = Math.round(Math.random() * 255);
}
function draw() {
ctx.globalCompositeOperation = 'source-over';
ctx.fillStyle = 'rgba(0, 0, 0, 0.1)';
ctx.fillRect(0, 0, W, H);
ctx.globalCompositeOperation = 'lighter';
for(var i = 0; i < particles.length; i++) {
var p = particles[i];
ctx.beginPath();
p.opacity = Math.round(p.remaining_life/p.life*100)/100
var gradient = ctx.createRadialGradient(p.location.x, p.location.y, 0, p.location.x, p.location.y, p.radius);
gradient.addColorStop(0, 'rgba('+p.r+', '+p.g+', '+p.b+', '+p.opacity+')');
gradient.addColorStop(0.5, 'rgba('+p.r+', '+p.g+', '+p.b+', '+p.opacity+')');
gradient.addColorStop(1, 'rgba('+p.r+', '+p.g+', '+p.b+', 0)');
ctx.fillStyle = gradient;
ctx.arc(p.location.x, p.location.y, p.radius, Math.PI*2, false);
ctx.fill();
p.remaining_life--;
p.radius--;
p.location.x += p.speed.x;
p.location.y += p.speed.y;
if(p.remaining_life < 0 || p.radius < 0) {
particles[i] = new particle();
}
}
}
setInterval(draw, 33);
</script>
</body>
</html>
```
阅读全文