Js雪花随风舞动飘落特效分享
Js代码如下 根据需求自行修改
var canvas = document.createElement('canvas');
canvas.id="snowCanvas";
canvas.style="margin: 0 auto;height: 100vh;width: 100vw;position: fixed;pointer-events: none;top: 0;overflow: hidden;z-index: 9999;"
document.body.appendChild(canvas);
var c = document.getElementById('snowCanvas'),
$ = c.getContext("2d"),
w = c.width = window.innerWidth,
h = c.height = window.innerHeight;
function makeItSnow() {
var snow,
arr = [],
num = 600, //雪花数量
tsc = 0.002, //0 - 垂直下落不抖动 抖动量
sp = 0.02; //速度
sc = 1.2, //大小散列值
t =200,
mv = 100,//飘落角度
min = 0.15; //雪花下落速度散列
for (var i = 0; i < num; ++i) {
snow = new Flake();
snow.y = Math.random() * (h + 50);
snow.x = Math.random() * w;
snow.t = Math.random() * (Math.PI * 2);
snow.sz = (100 / (10 + (Math.random() * 100))) * sc;
snow.sp = (Math.pow(snow.sz * .8, 2) * .15) * sp;
snow.sp = snow.sp < min ? min : snow.sp;
arr.push(snow);
}
go();
function go(){
window.requestAnimationFrame(go);
$.clearRect(0, 0, w, h);
$.fillRect(0, 0, w, h);
$.fill();
for (var i = 0; i < arr.length; ++i) {
f = arr[i];
f.t += .05;
f.t = f.t >= Math.PI * 2 ? 0 : f.t;
f.y += f.sp;
f.x += Math.sin(f.t * tsc) * (f.sz * .3);
if (f.y > h + 50) f.y = -10 - Math.random() * mv;
if (f.x > w + mv) f.x = - mv;
if (f.x < - mv) f.x = w + mv;
f.draw();
}
}
function Flake() {
this.draw = function() {
this.g = $.createRadialGradient(this.x, this.y, 0, this.x, this.y, this.sz);
this.g.addColorStop(0, 'hsla(255,255%,255%,1)');
this.g.addColorStop(1, 'hsla(255,255%,255%,0)');
$.moveTo(this.x, this.y);
$.fillStyle = this.g;
$.beginPath();
$.arc(this.x, this.y, this.sz, 0, Math.PI * 2, true);
$.fill();
}
}
}
window.addEventListener('resize', function(){
c.width = w = window.innerWidth;
c.height = h = window.innerHeight;
}, false);
makeItSnow();
发表评论