最近在写接口,反正环境也有了,无聊写点代码
<!DOCTYPE html>
<html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>粒子效果</title>
<style>
body {
margin: 0;
padding: 0;
overflow: hidden;
}
canvas {
background-color: #000;
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
</style>
</head>
<body>
<canvas id="canvas" width="1232" height="645"></canvas>
<script>
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
const particles = [];
function createParticle(x, y) {
const size = Math.random() * 20 + 10; // 随机给粒子大小
const speed = (size / 30) * (Math.random() * 4 + 1); // 根据粒子的大小确定速度
const brightness = (size / 30) * 100; // 根据粒子的大小确定亮度
const particle = {
x,
y,
size,
color: getRandomColor(),
speedX: speed,
speedY: speed,
brightness: brightness
};
particles.push(particle);
}
function getRandomColor() {
const letters = '0123456789ABCDEF';
let color = '#';
for (let i = 0; i < 6; i++) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
function animate() {
requestAnimationFrame(animate);
ctx.clearRect(0, 0, canvas.width, canvas.height);
for (let i = 0; i < particles.length; i++) {
const particle = particles[i];
particle.x += particle.speedX;
particle.y += particle.speedY;
ctx.beginPath();
ctx.arc(particle.x, particle.y, particle.size, 0, Math.PI * 2);
ctx.fillStyle = particle.color;
ctx.globalAlpha = particle.brightness / 100;
ctx.fill();
if (particle.x - particle.size > canvas.width ||
particle.x + particle.size < 0 ||
particle.y - particle.size > canvas.height ||
particle.y + particle.size < 0) {
particles.splice(i, 1);
i--;
}
}
}
function init() {
canvas.addEventListener('mousemove', function(e) {
const { clientX, clientY } = e;
createParticle(clientX, clientY);
});
animate();
}
init();
</script>
</body></html>
效果如下: