用js写一个烟花效果
时间: 2024-01-03 09:03:50 浏览: 120
好的,以下是一个简单的用 JavaScript 实现烟花效果的示例代码:
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>烟花效果</title>
<style>
canvas {
display: block;
margin: 0 auto;
}
</style>
</head>
<body>
<canvas id="canvas"></canvas>
<script>
var canvas = document.getElementById('canvas');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
var ctx = canvas.getContext('2d');
function random(min, max) {
return Math.random() * (max - min) + min;
}
function Particle() {
this.x = canvas.width / 2;
this.y = canvas.height / 2;
this.vx = random(-5, 5);
this.vy = random(-15, -5);
this.color = 'rgb(' + Math.floor(random(0, 255)) + ',' + Math.floor(random(0, 255)) + ',' + Math.floor(random(0, 255)) + ')';
this.size = random(5, 10);
this.alpha = 1;
this.gravity = 0.2;
}
Particle.prototype.update = function() {
this.x += this.vx;
this.y += this.vy;
this.vy += this.gravity;
this.alpha -= 0.01;
};
Particle.prototype.draw = function() {
ctx.beginPath();
ctx.arc(this.x, this.y, this.size, 0, Math.PI * 2);
ctx.fillStyle = this.color;
ctx.globalAlpha = this.alpha;
ctx.closePath();
ctx.fill();
};
var particles = [];
function createParticles(x, y) {
for (var i = 0; i < 100; i++) {
var p = new Particle();
p.x = x;
p.y = y;
particles.push(p);
}
}
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
for (var i = 0; i < particles.length; i++) {
var p = particles[i];
p.update();
p.draw();
}
particles = particles.filter(function(p) {
return p.alpha > 0;
});
requestAnimationFrame(draw);
}
canvas.addEventListener('click', function(event) {
createParticles(event.clientX, event.clientY);
});
draw();
</script>
</body>
</html>
```
这段代码实现了点击 canvas 时在点击处创建一组烟花粒子,随着时间的推移,粒子逐渐消失。粒子的位置、速度、颜色、大小和透明度都是随机生成的,从而形成了烟花的效果。
阅读全文