鼠标特效

· · 个人记录

省流:吃水煮黑背鲈化学和物理学中毒了

我们认为我们可以把化学中的原子结构搬到电脑上,然后就做出来了这一坨东西。

本质上是在鼠标周围创建一些围绕鼠标转的小球,但是很好看。

::::info[代码(请使用篡改猴)]

// ==UserScript==
// @name         鼠标引力粒子特效
// @namespace    http://tampermonkey.net/
// @version      1.0
// @description  线段树好用!
// @author       Yang_YL
// @include      *
// @grant        none
// ==/UserScript==

(function() {
    'use strict';

    // ==================== 配置参数(带行内注释)====================
    const CONFIG = {
        // 基础粒子数
        PARTICLE_COUNT: 5,              // 粒子数量(推荐3-8个)

        // 引力参数
        GRAVITY_MAX: 0.75,                // 最大引力加速度(值越大粒子越靠近鼠标)
        SMOOTH_RADIUS: 120,               // 平滑半径:距离小于此值时引力近似线性,大于此值时趋于常数

        // 运动限制
        MAX_SPEED: 8,                      // 最大速度(像素/帧),防止粒子飞得过快
        PARTICLE_SIZE: 3,                  // 粒子绘制半径(像素)

        // 粒子质量(影响加速度,质量越大越难被拉动)
        MASS_RANGE: [0.5, 2.0],            // 质量随机范围 [最小值, 最大值]

        // 初始化位置(围绕鼠标)
        INIT_DIST_MIN: 50,                  // 初始化时距离鼠标的最小距离(像素)
        INIT_DIST_MAX: 120,                  // 初始化时距离鼠标的最大距离(像素)
        INIT_SPEED_MIN: 2.0,                 // 初始速度最小值(像素/帧)
        INIT_SPEED_MAX: 4.0,                 // 初始速度最大值(像素/帧)

        // 鼠标按下加速效果
        PRESS_SPEED_BOOST: 2.0,               // 按下鼠标时速度倍增系数
        PRESS_BOOST_MAX_SPEED: 14,            // 加速时的临时最大速度(松开后恢复)

        // 粒子间斥力(防止重叠)
        REPULSION_STRENGTH: 0.4,              // 斥力强度(值越大排斥越强)
        REPULSION_RANGE: 35,                   // 斥力作用范围(像素),距离小于此值开始排斥

        // 鼠标排斥(防止粒子堆积在鼠标点上)
        MOUSE_REPULSION_STRENGTH: 0.8,         // 鼠标排斥强度
        MOUSE_REPULSION_RANGE: 15,              // 鼠标排斥范围(像素)

        // 鼠标位置平滑滤波(防止鼠标移动时速度突变)
        MOUSE_SMOOTH_FACTOR: 0.25,            // 平滑因子(0~1,越小越平滑)

        // 拖尾效果(线条)
        TRAIL_LENGTH: 25,                     // 每个粒子记录的轨迹点数(决定拖尾长度)
        TRAIL_LINE_WIDTH_START: 3,             // 拖尾起始线宽(最新点,像素)
        TRAIL_LINE_WIDTH_END: 0.5,              // 拖尾结束线宽(最旧点,像素)
        TRAIL_OPACITY_START: 0.6,               // 拖尾起始透明度(最新点,0~1)
        TRAIL_OPACITY_END: 0.02,                 // 拖尾结束透明度(最旧点,0~1)

        // 颜色池
        COLORS: ['#FF6B6B', '#4ECDC4', '#45B7D1', '#96CEB4', '#FFEEAD', '#D4A5A5', '#9B59B6', '#3498DB']
    };


    let canvas, ctx;
    let width, height;
    let smoothMouseX = -1000, smoothMouseY = -1000;
    let rawMouseX = -1000, rawMouseY = -1000;
    let mousePresent = false;
    let particles = [];
    let boostActive = false;

    function gravitationalAcceleration(r, mass) {
        const denom = Math.sqrt(r * r + CONFIG.SMOOTH_RADIUS * CONFIG.SMOOTH_RADIUS);
        return CONFIG.GRAVITY_MAX * (r / denom) / mass;
    }

    class Particle {
        constructor() {
            this.mass = Math.random() * (CONFIG.MASS_RANGE[1] - CONFIG.MASS_RANGE[0]) + CONFIG.MASS_RANGE[0];
            this.resetNearMouse();
            this.color = CONFIG.COLORS[Math.floor(Math.random() * CONFIG.COLORS.length)];
            this.originalColor = this.color;
            this.trail = [];
            this.boostFlash = false;
        }

        update() {
            // 引力
            if (mousePresent) {
                const dx = smoothMouseX - this.x;
                const dy = smoothMouseY - this.y;
                const r = Math.sqrt(dx * dx + dy * dy);
                if (r >= 0.5) {
                    const accMag = gravitationalAcceleration(r, this.mass);
                    const ax = accMag * (dx / r);
                    const ay = accMag * (dy / r);
                    this.vx += ax;
                    this.vy += ay;
                }
            }

            // 鼠标排斥
            if (mousePresent) {
                const dx = this.x - smoothMouseX;
                const dy = this.y - smoothMouseY;
                const r = Math.sqrt(dx * dx + dy * dy);
                if (r < CONFIG.MOUSE_REPULSION_RANGE && r > 0.1) {
                    const force = CONFIG.MOUSE_REPULSION_STRENGTH * (1 - r / CONFIG.MOUSE_REPULSION_RANGE) / this.mass;
                    const normX = dx / r;
                    const normY = dy / r;
                    this.vx += force * normX;
                    this.vy += force * normY;
                }
            }

            // 粒子间斥力
            for (let other of particles) {
                if (other === this) continue;
                const dx = this.x - other.x;
                const dy = this.y - other.y;
                const dist = Math.sqrt(dx * dx + dy * dy);
                if (dist < CONFIG.REPULSION_RANGE && dist > 0.1) {
                    const force = CONFIG.REPULSION_STRENGTH * (1 - dist / CONFIG.REPULSION_RANGE) / this.mass;
                    const normX = dx / dist;
                    const normY = dy / dist;
                    this.vx += force * normX;
                    this.vy += force * normY;
                }
            }

            // 速度限制
            const currentMaxSpeed = boostActive ? CONFIG.PRESS_BOOST_MAX_SPEED : CONFIG.MAX_SPEED;
            const sp = Math.sqrt(this.vx * this.vx + this.vy * this.vy);
            if (sp > currentMaxSpeed) {
                this.vx = (this.vx / sp) * currentMaxSpeed;
                this.vy = (this.vy / sp) * currentMaxSpeed;
            }

            this.x += this.vx;
            this.y += this.vy;
            this.updateTrail();

            // 加速闪烁
            this.color = this.boostFlash ? '#FFFFFF' : this.originalColor;
        }

        updateTrail() {
            this.trail.push({ x: this.x, y: this.y });
            if (this.trail.length > CONFIG.TRAIL_LENGTH) {
                this.trail.shift();
            }
        }

        draw() {
            // 绘制拖尾线条(新点粗、旧点细)
            if (this.trail.length >= 2) {
                for (let i = 0; i < this.trail.length - 1; i++) {
                    const p1 = this.trail[i];
                    const p2 = this.trail[i+1];
                    const t = (i + 1) / (this.trail.length - 1);
                    const lineWidth = CONFIG.TRAIL_LINE_WIDTH_START * t + CONFIG.TRAIL_LINE_WIDTH_END * (1 - t);
                    const opacity = CONFIG.TRAIL_OPACITY_START * t + CONFIG.TRAIL_OPACITY_END * (1 - t);

                    ctx.beginPath();
                    ctx.moveTo(p1.x, p1.y);
                    ctx.lineTo(p2.x, p2.y);
                    ctx.strokeStyle = hexToRgba(this.originalColor, opacity);
                    ctx.lineWidth = lineWidth;
                    ctx.lineCap = 'round';
                    ctx.lineJoin = 'round';
                    ctx.stroke();
                }
            }

            // 绘制当前粒子(稍大,带光晕)
            ctx.beginPath();
            ctx.arc(this.x, this.y, CONFIG.PARTICLE_SIZE * 1.3, 0, Math.PI * 2);
            ctx.fillStyle = this.color;
            ctx.fill();
            ctx.shadowColor = this.color;
            ctx.shadowBlur = 10;
            ctx.fill();
            ctx.shadowBlur = 0;
        }

        resetNearMouse() {
            const targetX = mousePresent ? smoothMouseX : (Math.random() * width);
            const targetY = mousePresent ? smoothMouseY : (Math.random() * height);
            if (mousePresent) {
                const angle = Math.random() * Math.PI * 2;
                const dist = CONFIG.INIT_DIST_MIN + Math.random() * (CONFIG.INIT_DIST_MAX - CONFIG.INIT_DIST_MIN);
                this.x = targetX + Math.cos(angle) * dist;
                this.y = targetY + Math.sin(angle) * dist;
                const tangent = angle + Math.PI / 2;
                const speed = CONFIG.INIT_SPEED_MIN + Math.random() * (CONFIG.INIT_SPEED_MAX - CONFIG.INIT_SPEED_MIN);
                this.vx = Math.cos(tangent) * speed;
                this.vy = Math.sin(tangent) * speed;
            } else {
                this.x = targetX;
                this.y = targetY;
                this.vx = (Math.random() - 0.5) * 3;
                this.vy = (Math.random() - 0.5) * 3;
            }
            this.trail = [];
        }

        boostSpeed() {
            this.vx *= CONFIG.PRESS_SPEED_BOOST;
            this.vy *= CONFIG.PRESS_SPEED_BOOST;
            this.boostFlash = true;
            setTimeout(() => { this.boostFlash = false; }, 200);
        }
    }

    function hexToRgba(hex, opacity) {
        let c = hex.substring(1);
        if (c.length === 3) c = c.split('').map(ch => ch + ch).join('');
        const r = parseInt(c.substring(0,2), 16);
        const g = parseInt(c.substring(2,4), 16);
        const b = parseInt(c.substring(4,6), 16);
        return `rgba(${r}, ${g}, ${b}, ${opacity})`;
    }

    function initCanvas() {
        canvas = document.createElement('canvas');
        canvas.style.position = 'fixed';
        canvas.style.top = '0';
        canvas.style.left = '0';
        canvas.style.width = '100%';
        canvas.style.height = '100%';
        canvas.style.pointerEvents = 'none';
        canvas.style.zIndex = '99999';
        document.body.appendChild(canvas);
        ctx = canvas.getContext('2d');
        resizeCanvas();
        window.addEventListener('resize', resizeCanvas);
    }

    function resizeCanvas() {
        width = window.innerWidth;
        height = window.innerHeight;
        canvas.width = width * (devicePixelRatio || 1);
        canvas.height = height * (devicePixelRatio || 1);
        ctx.scale(devicePixelRatio || 1, devicePixelRatio || 1);
    }

    function initParticles() {
        particles = [];
        for (let i = 0; i < CONFIG.PARTICLE_COUNT; i++) {
            particles.push(new Particle());
        }
    }

    function trackMouse() {
        window.addEventListener('mousemove', (e) => {
            rawMouseX = e.clientX;
            rawMouseY = e.clientY;
            mousePresent = true;
        });
        window.addEventListener('mouseleave', () => { mousePresent = false; });
        window.addEventListener('mouseenter', (e) => {
            rawMouseX = e.clientX;
            rawMouseY = e.clientY;
            smoothMouseX = rawMouseX;
            smoothMouseY = rawMouseY;
            mousePresent = true;
        });

        window.addEventListener('mousedown', () => {
            boostActive = true;
            particles.forEach(p => p.boostSpeed());
            setTimeout(() => { boostActive = false; }, 300);
        });
    }

    function updateSmoothMouse() {
        if (mousePresent) {
            const alpha = CONFIG.MOUSE_SMOOTH_FACTOR;
            smoothMouseX = smoothMouseX * (1 - alpha) + rawMouseX * alpha;
            smoothMouseY = smoothMouseY * (1 - alpha) + rawMouseY * alpha;
        }
    }

    function checkBounds() {
        for (let p of particles) {
            if (p.x < -400 || p.x > width + 400 || p.y < -400 || p.y > height + 400) {
                p.resetNearMouse();
            }
        }
    }

    function animate() {
        updateSmoothMouse();
        ctx.clearRect(0, 0, width, height);
        for (let p of particles) {
            p.update();
            p.draw();
        }
        checkBounds();
        requestAnimationFrame(animate);
    }

    function start() {
        initCanvas();
        trackMouse();
        smoothMouseX = rawMouseX;
        smoothMouseY = rawMouseY;
        setTimeout(() => {
            initParticles();
            animate();
        }, 100);
    }

    start();
})();

:::: 叠甲:前面忘了,我的贡献大于 ai,后面忘了。

变量上有注释,可以自己修改。