如何用前端实现炫酷粒子效果(HTML)
在HTML中实现炫酷的粒子效果,我们可以使用canvas
元素和JavaScript。以下是一个简单的例子,展示了如何用原生JavaScript创建这种效果:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Cool Particle Effect</title>
<style>
canvas {
position: absolute;
width: 100%;
height: 100%;
top: 0;
left: 0;
}
</style>
</head>
<body>
<canvas id="particle-canvas"></canvas>
<script>
const canvas = document.getElementById('particle-canvas');
const ctx = canvas.getContext('2d');
const particles = [];
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
class Particle {
constructor(x, y) {
this.x = x;
this.y = y;
this.radius = Math.random() * 1.5;
this.color = 'rgba(255,255,255,' + Math.random() / 5 + ')';
this.dx = Math.random() * 2 - 1;
this.dy = Math.random() * 2 - 1;
}
draw() {
ctx.beginPath();
ctx.arc(this.x, this.y, this.radius, 0, 2 * Math.PI, false);
ctx.fillStyle = this.color;
ctx.fill();
}
update() {
this.x += this.dx;
this.y += this.dy;
if (this.x - this.radius > canvas.width || this.x + this.radius < 0) {
this.dx = -this.dx;
}
if (this.y - this.radius > canvas.height || this.y + this.radius < 0) {
this.dy = -this.dy;
}
}
}
function init() {
particles.push(new Particle(Math.random() * canvas.width, Math.random() * canvas.height));
}
function animate() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
for (let i = 0; i < particles.length; i++) {
particles[i].draw();
particles[i].update();
}
requestAnimationFrame(animate);
}
// 初始化粒子
for (let i = 0; i < 100; i++) {
init();
}
// 开始动画
animate();
</script>
</body>
</html>
这段代码会在页面上创建一个全屏的粒子效果,你可以通过调整particles.length
的初始值来增减粒子的数量,或者修改粒子的颜色、大小等属性来自定义粒子效果。
评论已关闭