// particles.js - CSDN 风格柔和粒子网格背景 (function() { 'use strict'; class ParticleSystem { constructor(options = {}) { this.canvas = null; this.ctx = null; this.particles = []; this.animationId = null; // CSDN 风格配置:极其 subtle this.config = { particleCount: options.particleCount || null, // 默认根据屏幕计算 connectionDistance: options.connectionDistance || 100, // 连线距离短 mouseDistance: options.mouseDistance || 120, // 鼠标影响范围 attractStrength: options.attractStrength || 0.04, // 极弱的吸引力 speed: options.speed || 0.4, // 缓慢的漂移速度 size: { min: 2, max: 4 }, // 极小的粒子 opacity: { min: 0.3, max: 0.6 }, // 很淡的透明度 zIndex: options.zIndex || -1, // 放在内容后面 colorLight: '100, 100, 100', // 浅灰色(亮色模式) colorDark: '150, 150, 150', // 中灰色(暗色模式) lineOpacity: 0.2, // 极淡的连线 maxConnections: 5, // 限制连线数量避免杂乱 bgColor: options.bgColor || null // 背景色(可选) }; this.mouse = { x: null, y: null, active: false }; this.isDark = false; this.dpr = window.devicePixelRatio || 1; this.init(); } init() { if (document.getElementById('particleCanvas')) return; this.canvas = document.createElement('canvas'); this.canvas.id = 'particleCanvas'; this.canvas.style.cssText = ` position: fixed; top: 0; left: 0; width: 100%; height: 100%; z-index: ${this.config.zIndex}; pointer-events: none; touch-action: none; opacity: 0.6; /* 整体再淡一点 */ `; document.body.insertBefore(this.canvas, document.body.firstChild); this.ctx = this.canvas.getContext('2d', { alpha: true }); this.resize(); window.addEventListener('resize', () => this.resize(), { passive: true }); this.initEvents(); this.initThemeListener(); this.createParticles(); this.visibilityHandler = () => { if (document.hidden) { if (this.animationId) cancelAnimationFrame(this.animationId); this.animationId = null; } else if (!this.animationId) { this.animate(); } }; document.addEventListener('visibilitychange', this.visibilityHandler); this.animate(); } initEvents() { // 鼠标移动(极其平滑的跟随) const updateMouse = (x, y) => { this.mouse.x = x; this.mouse.y = y; this.mouse.active = true; // 延迟取消 active 状态,避免闪烁 clearTimeout(this.mouseTimer); this.mouseTimer = setTimeout(() => { this.mouse.active = false; }, 100); }; window.addEventListener('mousemove', (e) => { updateMouse(e.clientX, e.clientY); }, { passive: true }); // 触摸支持 window.addEventListener('touchstart', (e) => { if (e.touches[0]) updateMouse(e.touches[0].clientX, e.touches[0].clientY); }, { passive: true }); window.addEventListener('touchmove', (e) => { if (e.touches[0]) updateMouse(e.touches[0].clientX, e.touches[0].clientY); }, { passive: true }); window.addEventListener('touchend', () => { this.mouse.active = false; }); } resize() { this.width = window.innerWidth; this.height = window.innerHeight; this.canvas.width = this.width * this.dpr; this.canvas.height = this.height * this.dpr; this.canvas.style.width = this.width + 'px'; this.canvas.style.height = this.height + 'px'; this.ctx.scale(this.dpr, this.dpr); // 根据屏幕面积计算粒子数:每 20000 像素一个粒子,最少 40,最多 100 if (!this.config.particleCount) { const area = this.width * this.height; this.targetCount = Math.min(Math.max(Math.floor(area / 20000), 40), 100); } } initThemeListener() { this.checkTheme(); const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)'); mediaQuery.addEventListener('change', () => this.checkTheme()); const observer = new MutationObserver(() => this.checkTheme()); observer.observe(document.documentElement, { attributes: true, attributeFilter: ['class', 'data-theme'] }); } checkTheme() { const html = document.documentElement; this.isDark = html.classList.contains('dark') || html.getAttribute('data-theme') === 'dark' || (!html.classList.contains('light') && window.matchMedia('(prefers-color-scheme: dark)').matches); } createParticles() { const count = this.config.particleCount || this.targetCount || 60; this.particles = []; // 清空已有 for (let i = 0; i < count; i++) { this.particles.push({ x: Math.random() * this.width, y: Math.random() * this.height, // 基础速度:极小的随机漂移 vx: (Math.random() - 0.75) * this.config.speed, vy: (Math.random() - 0.75) * this.config.speed, size: Math.random() * (this.config.size.max - this.config.size.min) + this.config.size.min, opacity: Math.random() * (this.config.opacity.max - this.config.opacity.min) + this.config.opacity.min, // 每个粒子有独立的相位,用于正弦波动,让运动更自然 phase: Math.random() * Math.PI * 2, phaseSpeed: 0.02 + Math.random() * 0.02 }); } } updateParticle(p) { // 正弦波动:让漂移更柔和自然 p.phase += p.phaseSpeed; const waveX = Math.sin(p.phase) * 0.1; const waveY = Math.cos(p.phase * 0.7) * 0.1; // 基础漂移 p.x += p.vx + waveX; p.y += p.vy + waveY; // 鼠标吸引效果(极其柔和) if (this.mouse.active && this.mouse.x !== null) { const dx = this.mouse.x - p.x; const dy = this.mouse.y - p.y; const dist = Math.sqrt(dx * dx + dy * dy); if (dist < this.config.mouseDistance) { // 距离越近吸引越弱(避免聚集太紧),越远吸引越强但总体很弱 const force = (1 - dist / this.config.mouseDistance) * this.config.attractStrength; p.vx += dx * force * 0.01; p.vy += dy * force * 0.01; } } // 速度限制和阻尼(保持柔和感) const maxSpeed = this.config.speed * 1.5; p.vx = Math.max(-maxSpeed, Math.min(maxSpeed, p.vx)); p.vy = Math.max(-maxSpeed, Math.min(maxSpeed, p.vy)); // 极小的阻尼,让速度慢慢回归基础值 p.vx *= 0.995; p.vy *= 0.995; // 软边界:不是硬反弹,而是慢慢转向 const margin = 50; if (p.x < -margin) p.x = this.width + margin; if (p.x > this.width + margin) p.x = -margin; if (p.y < -margin) p.y = this.height + margin; if (p.y > this.height + margin) p.y = -margin; } draw() { const color = this.isDark ? this.config.colorDark : this.config.colorLight; // 绘制连线(在粒子下层) this.drawConnections(color); // 绘制粒子 this.particles.forEach(p => { this.ctx.beginPath(); this.ctx.arc(p.x, p.y, p.size, 0, Math.PI * 2); this.ctx.fillStyle = `rgba(${color}, ${p.opacity})`; this.ctx.fill(); }); } drawConnections(color) { // 只检查部分粒子对,优化性能 for (let i = 0; i < this.particles.length; i++) { let connections = 0; const p1 = this.particles[i]; // 只检查附近的粒子(简单空间分割思想:只检查索引接近的) for (let j = i + 1; j < Math.min(i + 20, this.particles.length); j++) { if (connections >= this.config.maxConnections) break; const p2 = this.particles[j]; const dx = p1.x - p2.x; const dy = p1.y - p2.y; const distSq = dx * dx + dy * dy; if (distSq < this.config.connectionDistance * this.config.connectionDistance) { const dist = Math.sqrt(distSq); const opacity = this.config.lineOpacity * (1 - dist / this.config.connectionDistance); this.ctx.beginPath(); this.ctx.moveTo(p1.x, p1.y); this.ctx.lineTo(p2.x, p2.y); this.ctx.strokeStyle = `rgba(${color}, ${opacity})`; this.ctx.lineWidth = 0.5; this.ctx.stroke(); connections++; } } } } animate() { this.ctx.clearRect(0, 0, this.width, this.height); this.particles.forEach(p => this.updateParticle(p)); this.draw(); this.animationId = requestAnimationFrame(() => this.animate()); } destroy() { if (this.animationId) cancelAnimationFrame(this.animationId); if (this.visibilityHandler) document.removeEventListener('visibilitychange', this.visibilityHandler); if (this.canvas && this.canvas.parentNode) { this.canvas.parentNode.removeChild(this.canvas); } window.particleSystem = null; } } // 自动初始化 function autoInit() { if (document.body?.hasAttribute('data-no-particles')) return; if (window.matchMedia('(prefers-reduced-motion: reduce)').matches) return; if (window.particleSystem) return; if (!document.body) { setTimeout(autoInit, 100); return; } const options = {}; if (document.body.dataset.particleCount) { options.particleCount = parseInt(document.body.dataset.particleCount); } window.particleSystem = new ParticleSystem(options); } window.ParticleSystem = ParticleSystem; window.initParticles = (opts) => new ParticleSystem(opts); if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', autoInit); } else { setTimeout(autoInit, 0); } })();