用JavaScript写一个粒子特效
时间: 2023-05-15 09:06:15 浏览: 78
好的,以下是一个简单的用 JavaScript 实现的粒子特效:
```javascript
// 创建画布
var canvas = document.createElement('canvas');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
document.body.appendChild(canvas);
// 获取画布上下文
var ctx = canvas.getContext('2d');
// 定义粒子类
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() * Math.PI * 2;
this.velocity = {
x: Math.cos(this.angle) * this.speed,
y: Math.sin(this.angle) * this.speed
};
}
// 更新粒子位置
Particle.prototype.update = function() {
this.x += this.velocity.x;
this.y += this.velocity.y;
};
// 绘制粒子
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();
};
// 创建粒子数组
var particles = [];
// 添加粒子到数组中
for (var i = 0; i < 100; i++) {
var x = canvas.width / 2;
var y = canvas.height / 2;
var radius = Math.random() * 5 + 2;
var color = 'rgba(255, 255, 255, 0.5)';
var speed = Math.random() * 3 + 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();
particles[i].draw();
}
}
// 开始动画
animate();
```
希望这个代码对你有帮助!