JavaScript满屏下雪特效代码

JavaScript满屏下雪特效代码
《冬日恋歌》是一款以简洁代码打造的数字雪景作品。它无需图像素材,仅通过精妙的 JavaScript 语句,便让雪花纷飞的冬日盛景在屏幕上绽放。

1. 冬日恋歌前言

这份 “ 冬日恋歌 ” 就像是一位隐藏在数字世界的冬之精灵,默默等待我们唤醒。不依赖任何图像素材,仅靠简洁有力的 jаvascript 语句,就能勾勒出雪花纷飞的美好画卷。

2. 冬日恋歌诞生

初始化函数 initsnow 宛如雪花的孵化巢。精准测量页面边界 ——marginbottom 与 marginright,为雪花们规划好活动范围。循环登场,像勤劳的工匠塑造每一片雪花:字体随机选定,大小在 snowminsize 到 snowmaxsize 间变化,颜色抽取点亮,位置坐标依据 snowingzone(全屏、左半边、中间、右半边任你挑)巧妙分布,初始速度 sinkspeed 赋予它们飘落的动感,一切准备就绪,只等上场。

movesnow 函数则是这场雪的管控者,让雪花持续舞动,依据 x_mv 数组掌控横向步伐,配合 sink 属性加速下落,还巧用正弦函数 Math.sin 让雪花左右摇曳,宛如风中精灵。一旦雪花触底或越界,立即重置位置,从顶部重生,永不停息地演绎冬日恋歌。

3. 实战部署

新建 snow.js 文件,保存 jаvascript 代码:

// 雪花飘落
/* 奥德彪学习网 https://www.aode8.com/ 
Snow Fall - no images - Java Script
 */
(function() {
    // 配置参数
    const config = {
        maxSnowflakes: 300,          // 最大雪花数量
        color: "#FFFFFF",            // 雪花颜色
        font: "Times",               // 雪花字体
        symbol: "❄",                 // 雪花符号
        sinkSpeed: 1,                // 基础下落速度
        maxSize: 25,                 // 最大雪花大小
        minSize: 15,                 // 最小雪花大小
        snowingZone: 1,              // 下雪区域 1-4
        zIndex: 1000                 // 雪花层级
    };

    // 全局变量
    let snowflakes = [];
    let bounds = {
        bottom: 0,
        right: 0
    };
    let animationId = null;

    // 工具函数:生成随机数
    const random = (range) => Math.floor(range * Math.random());

    // 更新边界尺寸
    const updateBounds = () => {
        bounds.bottom = document.body.scrollHeight;
        bounds.right = window.innerWidth - 15;
    };

    // 初始化雪花
    const initSnowflakes = () => {
        // 创建雪花容器
        const container = document.createElement('div');
        container.style.cssText = `
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            pointer-events: none;
            overflow: hidden;
        `;
        document.body.appendChild(container);

        const sizeRange = config.maxSize - config.minSize;
        
        // 创建雪花元素
        for (let i = 0; i < config.maxSnowflakes; i++) {
            // 创建雪花元素
            const snowEl = document.createElement('span');
            snowEl.id = `snowflake-${i}`;
            snowEl.textContent = config.symbol;
            snowEl.style.cssText = `
                position: absolute;
                top: -${config.maxSize}px;
                z-index: ${config.zIndex};
                color: ${config.color};
                font-family: ${config.font};
            `;
            
            container.appendChild(snowEl);

            // 雪花属性
            const size = random(sizeRange) + config.minSize;
            const zoneConfig = [
                { offset: 0, width: bounds.right },
                { offset: 0, width: bounds.right / 2 },
                { offset: bounds.right / 4, width: bounds.right / 2 },
                { offset: bounds.right / 2, width: bounds.right / 2 }
            ][config.snowingZone - 1];

            // 存储雪花状态
            snowflakes[i] = {
                element: snowEl,
                size: size,
                sink: config.sinkSpeed * size / 5,
                posX: random(zoneConfig.width - size) + zoneConfig.offset,
                posY: random(2 * bounds.bottom - bounds.bottom - 2 * size),
                xMovement: 0.03 + Math.random() / 10,
                leftRightOffset: Math.random() * 15,
                coordinates: 0
            };

            // 应用初始样式
            snowEl.style.fontSize = `${size}px`;
            snowEl.style.left = `${snowflakes[i].posX}px`;
            snowEl.style.top = `${snowflakes[i].posY}px`;
        }
    };

    // 移动雪花
    const moveSnowflakes = () => {
        for (let i = 0; i < snowflakes.length; i++) {
            const flake = snowflakes[i];
            
            // 更新位置和坐标
            flake.coordinates += flake.xMovement;
            flake.posY += flake.sink;
            
            // 应用位置(加入正弦曲线实现左右摇摆)
            flake.element.style.left = `${flake.posX + flake.leftRightOffset * Math.sin(flake.coordinates)}px`;
            flake.element.style.top = `${flake.posY}px`;

            // 雪花超出边界时重置
            if (flake.posY >= bounds.bottom - 2 * flake.size || 
                parseInt(flake.element.style.left) > (bounds.right - 3 * flake.leftRightOffset)) {
                
                const zoneConfig = [
                    { offset: 0, width: bounds.right },
                    { offset: 0, width: bounds.right / 2 },
                    { offset: bounds.right / 4, width: bounds.right / 2 },
                    { offset: bounds.right / 2, width: bounds.right / 2 }
                ][config.snowingZone - 1];
                
                flake.posX = random(zoneConfig.width - flake.size) + zoneConfig.offset;
                flake.posY = 0;
            }
        }
        
        // 使用requestAnimationFrame实现平滑动画
        animationId = requestAnimationFrame(moveSnowflakes);
    };

    // 初始化函数
    const init = () => {
        // 检查浏览器环境
        if (typeof window === 'undefined' || typeof document === 'undefined') return;
        
        // 初始化边界
        updateBounds();
        
        // 监听窗口大小变化
        window.addEventListener('resize', updateBounds);
        
        // 创建雪花并开始动画
        initSnowflakes();
        moveSnowflakes();
    };

    // 页面加载完成后初始化
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', init);
    } else {
        init();
    }

    // 清理函数(可选)
    window.stopSnowfall = () => {
        if (animationId) {
            cancelAnimationFrame(animationId);
        }
        const container = document.querySelector('div[style*="pointer-events: none"]');
        if (container) container.remove();
        snowflakes = [];
    };
})();

 

将 snow.js 文件上传至服务器中,引入脚本:

 

<script type="text/JavaScript" language="JavaScript" src="这里修改为 snow.js 文件路径"></script>

这场雪,不仅赋予我们定制数字冬景的能力,更能窥探到 jаvascript 编程的魅力。快试试吧!

📢 2025年,技术达人代码无 Bug,创意灵感永不枯竭;愿莘莘学子学业有成,每一次都换来丰硕回报;愿逐梦者事业高升,所行皆坦途,所遇皆美好。愿家人健康常伴,团圆时刻岁岁温馨。

阅读剩余