当前位置 : 主页 > 网络编程 > JavaScript >

js 下雪效果

来源:互联网 收集:自由互联 发布时间:2021-06-28
js 下雪 ;(function() { var Canvas = function(w, h) {this.width = w;this.height = h; }; var Snow = function() {}; Canvas.prototype = {init: function () { var oC = document.createElement("canvas"); oC.setAttribute('width', this.width); oC.s
js 下雪
;(function() {
    var Canvas = function(w, h) {
		this.width = w;
		this.height = h;
    };

    var Snow = function() {};

   	Canvas.prototype = {
		init: function () {
	        var oC = document.createElement("canvas");
	        oC.setAttribute('width', this.width);
	        oC.setAttribute('height', $("html").height());
	        oC.setAttribute('id', 'canvas');
	        document.body.appendChild(oC);
	    }
   	};

	Snow.prototype = {
		random: function (min, max) {
            return Math.random() * (max - min) + min;
        },
	    init: function () {
            this.x = this.random(0, width);
            this.y = 0;
            this.r = this.random(1, 5);
            this.vy = this.random(3, 5);
        },
        draw: function (cxt) {
            cxt.beginPath();
            cxt.fillStyle = 'white';
            cxt.arc(this.x, this.y + this.r, this.r, 0, Math.PI * 2, false);
            cxt.fill();
            cxt.closePath();
            this.update(cxt);
        },
        update: function (cxt) {
            if (this.y < height - this.r) {
                this.y += this.vy;
            } else {
                this.init();
            }
        }
	}

	var curWinWidth = window.innerWidth,
	    curWinHeight = window.innerHeight;
	var oCanvas = new Canvas(curWinWidth, curWinHeight);
	oCanvas.init();

	var oC = document.querySelector('#canvas');
	var width = oC.width, height = oC.height, oGc = oC.getContext('2d');

	var snow = [];
	for (var i = 0; i < 50; i++) {
		var timeoutId = null;
		clearTimeout(timeoutId);

	    timeoutId = setTimeout(function () {
	        var oSnow = new Snow();
	        oSnow.init();
	        snow.push(oSnow);
	    }, 500 * i);
	}

	(function move() {
	    oGc.clearRect(0, 0, width, height);
	    for (var i = 0; i < snow.length; i++) {
	        snow[i].draw(oGc);
	    }
	    requestAnimationFrame(move);
	})();
})();
网友评论