这次给大家带来js实现雪花飘落动画步骤详解,js实现雪花飘落动画的注意事项有哪些,下面就是实战案例,一起来看一下。
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<title>js下雪动画</title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<style>
.masthead {
background-color:#333;
display:block;
width:100%;
height:400px;
}
</style>
<body>
<p class="masthead"></p>
<script>
(function () {
var count = 300;
var masthead = document.queryselector('.masthead');
var canvas = document.createelement('canvas');
var ctx = canvas.getcontext('2d');
var width = masthead.clientwidth;
var height = masthead.clientheight;
var i = 0;
var active = false;
function onresize() {
width = masthead.clientwidth;
height = masthead.clientheight;
canvas.width = width;
canvas.height = height;
ctx.fillstyle = '#fff';
var wasactive = active;
active = width > 600;
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 < count; i++) {
snowflake = new snowflake();
snowflakes.push(snowflake);
}
function update() {
ctx.clearrect(0, 0, width, height);
if (!active)
return;
for (i = 0; i < count; 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, 1000 / 60);
};
})();
onresize();
window.addeventlistener('resize', onresize, false);
masthead.appendchild(canvas);
})();
</script></body></html>
使用本站html/css/js在线运行测试工具:http://tools.jb51.net/code/htmljsrun,可得到如下测试运行效果:
相信看了本文案例你已经掌握了方法,更多精彩请关注其它相关文章!
推荐阅读:
jquery如何判断元素内容为空
vue.js双向绑定项目实战分析
以上就是js实现雪花飘落动画步骤详解的详细内容。