用html写一个粒子特效
时间: 2023-05-15 17:06:15 浏览: 56
好的,以下是一个简单的粒子特效的HTML代码:
```html
<!DOCTYPE html>
<html>
<head>
<title>粒子特效</title>
<style>
body {
margin: 0;
padding: 0;
background-color: #000;
}
canvas {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
</style>
</head>
<body>
<canvas id="canvas"></canvas>
<script>
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var particles = [];
function Particle(x, y, radius, color, speed) {
this.x = x;
this.y = y;
this.radius = radius;
this.color = color;
this.speed = speed;
this.angle = Math.random() * 360;
this.velocity = {
x: Math.cos(this.angle) * this.speed,
y: Math.sin(this.angle) * this.speed
};
this.gravity = 0.05;
this.friction = 0.95;
}
Particle.prototype.draw = function() {
ctx.beginPath();
ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2, false);
ctx.fillStyle = this.color;
ctx.fill();
ctx.closePath();
}
Particle.prototype.update = function() {
this.velocity.x *= this.friction;
this.velocity.y *= this.friction;
this.velocity.y += this.gravity;
this.x += this.velocity.x;
this.y += this.velocity.y;
this.draw();
}
function createParticles() {
for (var i = 0; i < 100; i++) {
var x = canvas.width / 2;
var y = canvas.height / 2;
var radius = Math.random() * 10 + 5;
var color = "rgb(" + Math.floor(Math.random() * 255) + "," + Math.floor(Math.random() * 255) + "," + Math.floor(Math.random() * 255) + ")";
var speed = Math.random() * 5 + 1;
particles.push(new Particle(x, y, radius, color, speed));
}
}
function animate() {
requestAnimationFrame(animate);
ctx.clearRect(0, 0, canvas.width, canvas.height);
for (var i = 0; i < particles.length; i++) {
particles[i].update();
}
}
createParticles();
animate();
</script>
</body>
</html>
```
这段代码会在页面上创建一个黑色背景的canvas元素,并在其中生成100个随机颜色、大小、速度的粒子,形成一个漂亮的粒子特效。