原生js+canvas实现下雪效果
程序员文章站
2022-07-07 11:44:48
本文实例为大家分享了js+canvas实现下雪效果的具体代码,供大家参考,具体内容如下效果展示:源码展示: &...
本文实例为大家分享了js+canvas实现下雪效果的具体代码,供大家参考,具体内容如下
效果展示:
源码展示:
<!doctype html> <html> <head> <meta charset="utf-8"> <title>canvas下雪效果(原生js)</title> <style> * { margin: 0; padding: 0 } html, body { width: 100%; height: 100%; overflow: hidden; background-color: #222; } #canvas { position: absolute; top: 0; left: 0; } </style> </head> <body> <canvas id="canvas"></canvas> <img id="imgsnow" width="0" height="0" src="xh.png" alt="雪花"> <img id="bgsnow" width="100%" height="100%" src="bj.jpg" alt="背景"> <script> window.onload = function () { var canvas = document.getelementbyid("canvas"); var imgsnow = document.getelementbyid("imgsnow"); var bgsnow = document.getelementbyid("bgsnow"); var ctx = canvas.getcontext('2d'); var mbody = document.queryselector("body"); canvas.width =mbody.offsetwidth; canvas.height = mbody.offsetheight; var getrandomnum = function (min, max) { var range = max - min; var rand = math.random(); return (min + math.round(rand * range)); } // console.log(getrandomnum(0, canvas.width)) var snowarray = {}; //雪花对象 var snowindex = 0; //标识符 var setting = { num: 30, //数量 snowsize: 20, //大小 startx: math.random() * canvas.width, //起始横坐标 starty: 0, //起始纵坐标 vy: 0.01 } function snow() { // 起始横坐标 this.x = math.random() * canvas.width; // 起始纵坐标 this.y = setting.starty; this.size = setting.snowsize + math.random() * 10 - 10; //横坐标偏移量 this.vx = math.random() * 3 - 2; //偏移量 //纵坐标偏移量 this.vy = math.random() * 10; this.life = 0; this.maxlife = 100; this.id = snowindex; //当前信息保存至对象snowarray snowarray[snowindex] = this; snowindex++; } snow.prototype.draw = function () { this.x += this.vx; this.y += this.vy; this.vy += setting.vy; this.life++; //删除 if (this.y > canvas.height * 0.9 - 20) { snowarray[this.id] } else if (this.life >= this.maxlife) { snowarray[this.id] } ctx.drawimage(imgsnow, this.x, this.y, this.size, this.size) } setinterval(function () { ctx.drawimage(bgsnow, 0, 0, canvas.width, canvas.height); //数 for (var i = 0; i < setting.num; i++) { if (math.random() > 0.97) { new snow(); } } for (var i in snowarray) { snowarray[i].draw(); } }, 100)202082104246954 } </script> </body> </html>
图片:
雪花:
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。