炫酷的JS粒子效果
<style>
#particle-container {
background-color: rgb(4, 59, 78);
}
</style>
<canvas id="particle-container"></canvas>
<script>
// 获取 canvas 元素
const canvas = document.getElementById('particle-container');
const ctx = canvas.getContext('2d');
// 设置 canvas 尺寸
canvas.width = window.innerWidth/2;
canvas.height = window.innerHeight/2;
// 粒子类
class Particle {
constructor(x, y) {
this.x = x;
this.y = y;
this.radius = Math.random() * 5 + 1;
this.color = `hsl(${Math.random() * 360}, 50%, 50%)`;
this.speedX = Math.random() * 2 - 1;
this.speedY = Math.random() * 2 - 1;
}
draw() {
ctx.beginPath();
ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2);
ctx.fillStyle = this.color;
ctx.fill();
ctx.closePath();
}
update() {
this.x += this.speedX;
this.y += this.speedY;
if (this.x - this.radius < 0 || this.x > canvas.width - this.radius) {
this.speedX *= -1;
}
if (this.y - this.radius < 0 || this.y > canvas.height - this.radius) {
this.speedY *= -1;
}
}
}
// 初始化粒子数组
const particles = [];
for (let i = 0; i < 100; i++) {
const x = Math.random() * canvas.width;
const y = Math.random() * canvas.height;
particles.push(new Particle(x, y));
}
// 动画函数
function animate() {
requestAnimationFrame(animate);
ctx.clearRect(0, 0, canvas.width, canvas.height);
particles.forEach(particle => {
particle.update();
particle.draw();
});
}
// 开始动画
animate();
</script>
实现效果: