1 (function move() { 2 oGc.clearRect(0, 0, width, height); 3 for (var i = 0; i < snow.length; i++) { 4 snow[i].draw(oGc); 5 } 6 requestAnimationFrame(move); 7 })();
完整的demo代码:
1 <head> 2 <meta charset="UTF-8"> 3 <meta content="width=device-width, initial-scale=1.0"> 4 <meta http-equiv="X-UA-Compatible" content="ie=edge"> 5 <title>雪花效果 - by ghostwu</title> 6 <!-- <script src="lib.js"></script> --> 7 <style> 8 * { 9 margin: 0; 10 padding: 0; 11 } 12 13 body { 14 overflow: hidden; 15 } 16 </style> 17 </head> 18 19 <body> 20 <script> 21 window.onload = function () { 22 var Canvas = function (w, h) { 23 this.width = w; 24 this.height = h; 25 } 26 Canvas.prototype = { 27 init: function () { 28 var oC = document.createElement("canvas"); 29 oC.setAttribute('width', this.width); 30 oC.setAttribute('height', this.height); 31 oC.setAttribute('id', 'canvas'); 32 oC.style.backgroundColor = '#000'; 33 document.body.appendChild(oC); 34 } 35 } 36 var curWinWidth = window.innerWidth, 37 curWinHeight = window.innerHeight; 38 var oCanvas = new Canvas(curWinWidth, curWinHeight); 39 oCanvas.init(); oC = document.querySelector('#canvas'); 42 var width = oC.width, height = oC.height, oGc = oC.getContext('2d'); random(min, max) { 45 return Math.random() * (max - min) + min; 46 } 47 var Snow = function () { 48 49 } 50 Snow.prototype = { 51 init: function () { 52 this.x = random(0, width); 53 this.y = 0; 54 this.r = random(1, 5); 55 this.vy = random(3, 5); 56 }, 57 draw: function (cxt) { 58 cxt.beginPath(); 59 cxt.fillStyle = 'white'; 60 cxt.arc(this.x, this.y + this.r, this.r, 0, Math.PI * 2, false); 61 cxt.fill(); 62 cxt.closePath(); 63 this.update(cxt); 64 }, 65 update: function (cxt) { 66 if (this.y < height - this.r) { 67 this.y += this.vy; 68 } else { 69 this.init(); 70 } 71 } 72 } snow = []; 75 for (var i = 0; i < 500; i++) { 76 setTimeout(function () { 77 var oSnow = new Snow(); 78 oSnow.init(); 79 snow.push(oSnow); 80 }, 10 * i); 81 } 82 83 (function move() { 84 oGc.clearRect(0, 0, width, height); 85 for (var i = 0; i < snow.length; i++) { 86 snow[i].draw(oGc); 87 } 88 requestAnimationFrame(move); 89 })(); 90 } 91 </script> 92 </body>
View Code