给我做个粒子动画的源码
时间: 2023-08-05 12:03:36 浏览: 52
以下是一个简单的粒子动画的 HTML、CSS、JavaScript 源码示例:
```html
<!DOCTYPE html>
<html>
<head>
<title>粒子动画</title>
<style>
body {
margin: 0;
padding: 0;
background-color: #111;
}
#canvas {
display: block;
position: absolute;
top: 0;
left: 0;
z-index: -1;
}
</style>
</head>
<body>
<canvas id="canvas"></canvas>
<script>
// 创建粒子对象
function Particle(x, y, radius) {
this.x = x;
this.y = y;
this.radius = radius;
this.color = 'white';
this.speed = {
x: -1 + Math.random() * 2,
y: -1 + Math.random() * 2
};
this.gravity = 0.01;
this.friction = 0.99;
}
// 更新粒子的位置和速度
Particle.prototype.update = function() {
this.speed.x *= this.friction;
this.speed.y *= this.friction;
this.speed.y += this.gravity;
this.x += this.speed.x;
this.y += this.speed.y;
};
// 绘制粒子
Particle.prototype.draw = function(ctx) {
ctx.beginPath();
ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2);
ctx.fillStyle = this.color;
ctx.fill();
};
// 创建画布和粒子
function createCanvas() {
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var particles = [];
var width = window.innerWidth;
var height = window.innerHeight;
var particleNum = 100;
canvas.width = width;
canvas.height = height;
// 初始化粒子
for (var i = 0; i < particleNum; i++) {
particles.push(new Particle(width / 2, height / 2, Math.random() * 2));
}
// 绘制和更新粒子
function draw() {
ctx.clearRect(0, 0, width, height);
for (var i = 0; i < particles.length; i++) {
var particle = particles[i];
particle.update();
particle.draw(ctx);
}
requestAnimationFrame(draw);
}
draw();
}
// 页面加载完成后创建画布和粒子
window.onload = function() {
createCanvas();
};
</script>
</body>
</html>
```
以上代码中,通过 HTML 中的 `canvas` 元素来创建画布,并通过 JavaScript 中的 `Particle` 对象来创建粒子。在 `Particle` 对象中,通过 `update` 函数来更新粒子的位置和速度,通过 `draw` 函数来绘制粒子。在 `createCanvas` 函数中,初始化粒子并绘制和更新粒子。此外,通过 `window.onload` 来监听页面加载完成事件,当页面加载完成后创建画布和粒子。你可以根据需要修改代码中的粒子数量、颜色、速度等参数来实现不同的效果。