html+js实现雪花飘落特效效果的两种方法

2020-10-11   阅读:4223   类型:前端   分类:jQuery    标签: jQuery

我们经常可以看到有些网站有雪花飘落的功能,这是如何做的呢?实际上用到了HTML、js和canvas,以下是个简单的例子供大家参考。

第一种效果展示:

GIF.gif

实现代码

1、前端HTML代码:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Document</title>
<script src="https://libs.baidu.com/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
   <style>
        .snow{
            width: 100%;
            height: 100vh;
            background: #000;
        }
    </style>
    <div></div>
<script src="snow.js"></script>
</body>
</html>

2、snow.js文件代码

"use strict";
(function () {

// SnowVolume will change the density of the snowflakes
var SnowVolume = 800;
var elem = document.querySelector('.snow');
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
var width = elem.clientWidth;
var height = elem.clientHeight;
var i = 0;
var active = false;

function onResize() {
	width = elem.clientWidth;
	height = elem.clientHeight;
	canvas.width = width;
	canvas.height = height;
	ctx.fillStyle = '#FFF';

	var wasActive = active;
	active = width > 700;

	if (!wasActive && active)
		requestAnimFrame(update);
}

var Snowflake = function () {
	this.x = 0;
	this.y = 0;
	this.vy = 0;
	this.vx = 0;
	this.r = 0;

	this.reset();
}

Snowflake.prototype.reset = function() {
	this.x = Math.random() * width;
	this.y = Math.random() * -height;
	this.vy = 1 + Math.random() * 3;
	this.vx = 0.5 - Math.random();
	this.r = 1 + Math.random() * 2;
	this.o = 0.5 + Math.random() * 0.5;
}

canvas.style.position = 'absolute';
canvas.style.left = canvas.style.top = '0';

var snowflakes = [], snowflake;
for (i = 0; i < SnowVolume; i++) {
	snowflake = new Snowflake();
	snowflake.reset();
	snowflakes.push(snowflake);
}

function update() {

	ctx.clearRect(0, 0, width, height);

	if (!active)
		return;

	for (i = 0; i < SnowVolume; i++) {
		snowflake = snowflakes[i];
		snowflake.y += snowflake.vy;
		snowflake.x += snowflake.vx;

		ctx.globalAlpha = snowflake.o;
		ctx.beginPath();
		ctx.arc(snowflake.x, snowflake.y, snowflake.r, 0, Math.PI * 2, false);
		ctx.closePath();
		ctx.fill();

		if (snowflake.y > height) {
			snowflake.reset();
		}
	}

	requestAnimFrame(update);
}

// shim layer with setTimeout fallback
window.requestAnimFrame = (function(){
	return  window.requestAnimationFrame       ||
	window.webkitRequestAnimationFrame ||
	window.mozRequestAnimationFrame    ||
	function( callback ){
		window.setTimeout(callback, 5000 / 60);
	};
})();

onResize();
window.addEventListener('resize', onResize, false);

elem.appendChild(canvas);
})();

第二种效果展示:

GIF.gif

代码实现

1、前端代码

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Document</title>
<script src="https://libs.baidu.com/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
   <style>
        body{
            width: 1000px;
            height: 1000px;
            background: #000;
        }
    </style>
</body>
</html>

2、JavaScript代码

<script>
    (function($){  
        $.fn.snow = function(options){  
        var $flake = $('<div/>').css({'position': 'absolute','z-index':'9999', 'top': '-50px'}).html('❄'),  
        documentHeight  = $(document).height(),
        documentWidth   = $(document).width(),  
        defaults = {  
            minSize     : 10,  
            maxSize     : 20,  
            newOn       : 1000,  
            flakeColor  : "#AFDAEF" /* 雪花颜色 */
        },
        options = $.extend({}, defaults, options);

        endPositionTop = documentHeight - documentHeight * 0.3;

        var interval= setInterval( function(){
        var startPositionLeft = Math.random() * documentWidth - 100,  
        startOpacity = 0.5 + Math.random(),  
        sizeFlake = options.minSize + Math.random() * options.maxSize,  

        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: 10, /* 定义雪花最小尺寸 */  
            maxSize: 45,/* 定义雪花最大尺寸 */  
            newOn: 3000  /* 定义密集程度,数字越小越密集,cup使用率越高,建议最高设置成3000 */
        });  
    });
</script>


腾讯云11.11上云拼团Go,2核2G3M云服务器 28元/年

‘简忆博客’微信公众号 扫码关注‘简忆博客’微信公众号,获取最新文章动态
转载:请说明文章出处“来源简忆博客”。http://tpxhm.com/fdetail/463.html

×
觉得文章有用就打赏一下文章作者
微信扫一扫打赏 微信扫一扫打赏
支付宝扫一扫打赏 支付宝扫一扫打赏

文章评论(0)

登录
简忆博客壁纸一
简忆博客壁纸二
简忆博客壁纸三
简忆博客壁纸四
简忆博客壁纸五
简忆博客壁纸六
简忆博客壁纸七
简忆博客壁纸八
头像

简忆博客
勤于学习,乐于分享

置顶推荐

打赏本站

如果你觉得本站很棒,可以通过扫码支付打赏哦!
微信扫码:你说多少就多少~
微信扫码
支付宝扫码:你说多少就多少~
支付宝扫码
×