以下是一个使用 JavaScript 和 Canvas 实现简单粒子效果的示例代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
body {
margin: 0;
overflow: hidden;
background-color: #000;
}
</style>
</head>
<body>
<canvas id="canvas"></canvas>
<script>
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
window.addEventListener('resize', () => {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
});
// 粒子类
class Particle {
constructor(x, y) {
this.x = x;
this.y = y;
this.vx = Math.random() * 2 - 1;
this.vy = Math.random() * 2 - 1;
this.radius = Math.random() * 3 + 1;
this.color = `rgba(255, 255, 255, ${Math.random()})`;
}
draw() {
ctx.beginPath();
ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2);
ctx.fillStyle = this.color;
ctx.fill();
}
update() {
this.x += this.vx;
this.y += this.vy;
if (this.x > canvas.width || this.x < 0) {
this.vx = -this.vx;
}
if (this.y > canvas.height || this.y < 0) {
this.vy = -this.vy;
}
this.draw();
}
}
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() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
particles.forEach(particle => particle.update());
requestAnimationFrame(animate);
}
animate();
</script>
</body>
</html>
基础概念:
优势:
应用场景:
可能遇到的问题及解决方法:
领取专属 10元无门槛券
手把手带您无忧上云