网站建设

分享两种圣诞节雪花特效JS代码(网站下雪效果)

Jager · 12月25日 · 2014年 16986次已读

今天是圣诞节,首先,张戈在这里祝所有朋友节日快乐!

虽然我对圣诞节并不感冒,不过既然是公开的博客,那还是搞搞气氛吧!测试了网上找的几个代码,下面分享一下我个人比较满意的 2 种。

看代码之前,先分享一下即时预览的方法:很简单,在 webkit 浏览器(比如谷歌)按下 F12,然后在 console 里面粘贴一下 JS 代码(不含前后的 script 标签),然后回车执行即可看到效果了。

分享两种圣诞节雪花特效JS代码(网站下雪效果)

一、下雪特效代码①

<script type="text/javascript">
(function($){
	$.fn.snow = function(options){
	var $flake = $('<div id="snowbox" />').css({'position': 'absolute','z-index':'9999', 'top': '-50px'}).html('&#10052;'),
	documentHeight 	= $(document).height(),
	documentWidth	= $(document).width(),
	defaults = {
		minSize		: 10,
		maxSize		: 20,
		newOn		: 1000,
		flakeColor	: "#AFDAEF" /* 此处可以定义雪花颜色,若要白色可以改为#FFFFFF */
	},
	options	= $.extend({}, defaults, options);
	var interval= setInterval( function(){
	var startPositionLeft = Math.random() * documentWidth - 100,
	startOpacity = 0.5 + Math.random(),
	sizeFlake = options.minSize + Math.random() * options.maxSize,
	endPositionTop = documentHeight - 200,
	endPositionLeft = startPositionLeft - 500 + Math.random() * 500,
	durationFall = documentHeight * 10 + Math.random() * 5000;
	$flake.clone().appendTo('body').css({
		left: startPositionLeft,
		opacity: startOpacity,
		'font-size': sizeFlake,
		color: options.flakeColor
	}).animate({
		top: endPositionTop,
		left: endPositionLeft,
		opacity: 0.2
	},durationFall,'linear',function(){
		$(this).remove()
	});
	}, options.newOn);
    };
})(jQuery);
$(function(){
    $.fn.snow({ 
	    minSize: 5, /* 定义雪花最小尺寸 */
	    maxSize: 50,/* 定义雪花最大尺寸 */
	    newOn: 300  /* 定义密集程度,数字越小越密集 */
    });
});
</script>

Ps:由于我博客背景是浅色的,所以把雪花改成了淡蓝色,如果喜欢其他颜色的,可以根据注释自行修改。

二、下雪特效代码②

<script type="text/javascript">
    /* 控制下雪 */
    function snowFall(snow) {
        /* 可配置属性 */
        snow = snow || {};
        this.maxFlake = snow.maxFlake || 200;   /* 最多片数 */
        this.flakeSize = snow.flakeSize || 10;  /* 雪花形状 */
        this.fallSpeed = snow.fallSpeed || 1;   /* 坠落速度 */
    }
    /* 兼容写法 */
    requestAnimationFrame = window.requestAnimationFrame ||
        window.mozRequestAnimationFrame ||
        window.webkitRequestAnimationFrame ||
        window.msRequestAnimationFrame ||
        window.oRequestAnimationFrame ||
        function(callback) { setTimeout(callback, 1000 / 60); };

    cancelAnimationFrame = window.cancelAnimationFrame ||
        window.mozCancelAnimationFrame ||
        window.webkitCancelAnimationFrame ||
        window.msCancelAnimationFrame ||
        window.oCancelAnimationFrame;
    /* 开始下雪 */
    snowFall.prototype.start = function(){
        /* 创建画布 */
        snowCanvas.apply(this);
        /* 创建雪花形状 */
        createFlakes.apply(this);
        /* 画雪 */
        drawSnow.apply(this)
    }
    /* 创建画布 */
    function snowCanvas() {
        /* 添加 Dom 结点 */
        var snowcanvas = document.createElement("canvas");
        snowcanvas.id = "snowfall";
        snowcanvas.width = window.innerWidth;
        snowcanvas.height = document.body.clientHeight;
        snowcanvas.setAttribute("style", "position:absolute; top: 0; left: 0; z-index: 1; pointer-events: none;");
        document.getElementsByTagName("body")[0].appendChild(snowcanvas);
        this.canvas = snowcanvas;
        this.ctx = snowcanvas.getContext("2d");
        /* 窗口大小改变的处理 */
        window.onresize = function() {
            snowcanvas.width = window.innerWidth;
            /* snowcanvas.height = window.innerHeight */
        }
    }
    /* 雪运动对象 */
    function flakeMove(canvasWidth, canvasHeight, flakeSize, fallSpeed) {
        this.x = Math.floor(Math.random() * canvasWidth);   /* x 坐标 */
        this.y = Math.floor(Math.random() * canvasHeight);  /* y 坐标 */
        this.size = Math.random() * flakeSize + 2;          /* 形状 */
        this.maxSize = flakeSize;                           /* 最大形状 */
        this.speed = Math.random() * 1 + fallSpeed;         /* 坠落速度 */
        this.fallSpeed = fallSpeed;                         /* 坠落速度 */
        this.velY = this.speed;                             /* Y 方向速度 */
        this.velX = 0;                                      /* X 方向速度 */
        this.stepSize = Math.random() / 30;                 /* 步长 */
        this.step = 0                                       /* 步数 */
    }
    flakeMove.prototype.update = function() {
        var x = this.x,
            y = this.y;
        /* 左右摆动(余弦) */
        this.velX *= 0.98;
        if (this.velY <= this.speed) {
            this.velY = this.speed
        }
        this.velX += Math.cos(this.step += .05) * this.stepSize;

        this.y += this.velY;
        this.x += this.velX;
        /* 飞出边界的处理 */
        if (this.x >= canvas.width || this.x <= 0 || this.y >= canvas.height || this.y <= 0) {
            this.reset(canvas.width, canvas.height)
        }
    };
    /* 飞出边界-放置最顶端继续坠落 */
    flakeMove.prototype.reset = function(width, height) {
        this.x = Math.floor(Math.random() * width);
        this.y = 0;
        this.size = Math.random() * this.maxSize + 2;
        this.speed = Math.random() * 1 + this.fallSpeed;
        this.velY = this.speed;
        this.velX = 0;
    };
    // 渲染雪花-随机形状(此处可修改雪花颜色!!!)
    flakeMove.prototype.render = function(ctx) {
        var snowFlake = ctx.createRadialGradient(this.x, this.y, 0, this.x, this.y, this.size);
        snowFlake.addColorStop(0, "rgba(255, 255, 255, 0.9)");  /* 此处是雪花颜色,默认是白色 */
        snowFlake.addColorStop(.5, "rgba(255, 255, 255, 0.5)"); /* 若要改为其他颜色,请自行查 */
        snowFlake.addColorStop(1, "rgba(255, 255, 255, 0)");    /* 找 16 进制的 RGB 颜色代码。 */
        ctx.save();
        ctx.fillStyle = snowFlake;
        ctx.beginPath();
        ctx.arc(this.x, this.y, this.size, 0, Math.PI * 2);
        ctx.fill();
        ctx.restore();
    };
    /* 创建雪花-定义形状 */
    function createFlakes() {
        var maxFlake = this.maxFlake,
            flakes = this.flakes = [],
            canvas = this.canvas;
        for (var i = 0; i < maxFlake; i++) {
            flakes.push(new flakeMove(canvas.width, canvas.height, this.flakeSize, this.fallSpeed))
        }
    }
    /* 画雪 */
    function drawSnow() {
        var maxFlake = this.maxFlake,
            flakes = this.flakes;
        ctx = this.ctx, canvas = this.canvas, that = this;
        /* 清空雪花 */
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        for (var e = 0; e < maxFlake; e++) {
            flakes[e].update();
            flakes[e].render(ctx);
        }
        /*  一帧一帧的画 */
        this.loop = requestAnimationFrame(function() {
            drawSnow.apply(that);
        });
    }
    /* 调用及控制方法 */
    var snow = new snowFall({maxFlake:500});
    snow.start();
</script>

使用方法:

方法①、复制其中一种 JS 代码,粘贴到网站</body>标签之前即可;

方法②、去掉代码前后的<script **>标签,然后将代码保存为 js 文件,最后在网站引用即可。

Ps:若没效果,请确认网页是否已载入 JQurey,如果没有请在下雪代码之前引入 JQ 即可。

22 条回应
  1. 小武 2014-12-25 · 15:00

    沙发?

    • avatar
      Jager 2014-12-25 · 15:08

      哇, :eek: 好快的手速。 :lol:

  2. 李阳博客 2014-12-25 · 15:16

    哈哈,发现博客联盟下雪了,圣诞快乐

    • avatar
      Jager 2014-12-25 · 15:17

      同乐同乐~~ :smile:

  3. 极品飞鸽 2014-12-25 · 21:04

    以前感觉这些效果很炫,但是看久了就觉得也就那样子~\(≧▽≦)/~啦啦啦

    • avatar
      Jager 2014-12-25 · 22:12

      :evil: 总是有人想要的。

  4. avatar
    Jager 2014-12-25 · 22:13

    搞着玩下不行么?生命在于折腾。

  5. 路小亚博客 2014-12-26 · 11:13

    圣诞节,老外的节日,我就不跟着凑热闹了

  6. 王语双个人站 2014-12-27 · 13:42

    我好了好久雪花效果。这下找着了。
    PS:周末了,过来看看,博主有双休吗,好好休息,别在搞垮别人之前先搞跨了自己。‘(*∩_∩*)′

  7. 幻杀博客 2014-12-28 · 19:02

    联盟也下雪了

  8. 爱偷笑 2014-12-28 · 21:31

    哈哈不错,可惜圣诞已经过了

  9. 环络科技 2014-12-30 · 13:08

    亲测可用,大赞博主

  10. 幻杀博客 2014-12-31 · 20:39

    联盟也下雪了,话说SAE好像也有这个特效。挖个jquery控制方向的。

  11. 飞檐走沟 2015-3-3 · 23:34

    有个问题想请教博主,为什么更改了雪花数量没什么变化呢? 改到50000和50 下雪效果都是一样的,强制刷新后也是,什么情况?

    • avatar
      Jager 2015-3-4 · 10:06

      第二段代码?

  12. 飞檐走沟 2015-3-4 · 12:53

    this.maxFlake = snow.maxFlake || 200; /* 最多片数 */
    就是这段代码啊 ,还有就是显示出来的效果不一样 ,我感觉就是比较散 ,你去我站看下 !

    • avatar
      Jager 2015-3-4 · 13:09

      这代码我也只是收集分享。。。不喜欢的话建议百度再找找其他的吧。

    • 云彩飞扬 2015-12-1 · 15:09

      var snow = new snowFall({maxFlake:60});改成var snow = new snowFall({maxFlake:600});

      • avatar
        Jager 2015-12-1 · 19:15

        这个可以有

  13. 挂电风扇 2016-2-3 · 17:14

    这个飘雪效果现在是不是没用了?1和2的方法我都试过了,好像没效果了。

    • avatar
      Jager 2016-2-4 · 21:55

      亲测无误,代码不会过期。

  14. 寻尘 2018-12-21 · 13:40

    下雪代码特效②放到网站后页面会出现横方向滚动条

  15. lewis 2020-12-11 · 15:34

    很不错, 已转载, 谢谢

  16. 將相 2021-12-24 · 13:50

    可以把两个复制粘贴到一起吗?