原生js+canvas實(shí)現(xiàn)下雪效果
本文實(shí)例為大家分享了js+canvas實(shí)現(xiàn)下雪效果的具體代碼,供大家參考,具體內(nèi)容如下
效果展示:
源碼展示:
<!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 src='http://www.aoyou183.cn/bcjs/xh.png' alt='雪花'><img src='http://www.aoyou183.cn/bcjs/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; //標(biāo)識符 var setting = { num: 30, //數(shù)量 snowSize: 20, //大小 startX: Math.random() * canvas.width, //起始橫坐標(biāo) startY: 0, //起始縱坐標(biāo) vy: 0.01 } function snow() { // 起始橫坐標(biāo) this.x = Math.random() * canvas.width; // 起始縱坐標(biāo) this.y = setting.startY; this.size = setting.snowSize + Math.random() * 10 - 10; //橫坐標(biāo)偏移量 this.vx = Math.random() * 3 - 2; //偏移量 //縱坐標(biāo)偏移量 this.vy = Math.random() * 10; this.life = 0; this.maxLife = 100; this.id = snowIndex; //當(dāng)前信息保存至對象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); //數(shù) 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>
圖片:
雪花:
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. 告別AJAX實(shí)現(xiàn)無刷新提交表單2. 詳解盒子端CSS動(dòng)畫性能提升3. CSS Hack大全-教你如何區(qū)分出IE6-IE10、FireFox、Chrome、Opera4. WMLScript的語法基礎(chǔ)5. 輕松學(xué)習(xí)XML教程6. HTML <!DOCTYPE> 標(biāo)簽7. CSS 使用Sprites技術(shù)實(shí)現(xiàn)圓角效果8. HTML DOM setInterval和clearInterval方法案例詳解9. XML入門精解之結(jié)構(gòu)與語法10. 詳解CSS偽元素的妙用單標(biāo)簽之美
