用JavaScript实现下雪效果

标签:JavaScript

对昨天的彩球不满意,又去做了个下雪的。其实只改了几句代码而已,OO真强大。
为避免某些人浏览器卡死,只设置了100个雪花。建议用Chrome浏览,Firefox会很慢,IE尚可。


代码如下:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gbk" />
<title>JavaScript下雪效果演示</title>
<meta name="author" content="keakon" />
<meta name="copyright" content="keakon.cn" />
<script type="text/javascript" src="wz_jsgraphics.js"></script>
<script type="text/javascript">
//返回随机数
function rnd(max, min) {
    if (min == undefined) {
        min = 0;
    }
    return(min + Math.floor(Math.random() * (max - min)));
}

function Snow() {
    this.graph = new jsGraphics("sky");
    this.init();
}

Snow.prototype.init = function() {
    this.x = rnd(400); //宽400px
    this.y = 0;
    this.size = rnd(25, 5);
}

Snow.prototype.show = function() {
    this.graph.clear();
    this.graph.drawImage("snow.gif", this.x, this.y, this.size, this.size);
    this.graph.paint();
    if (this.y >= 300) { //高300px
        this.init();
    } else {
        this.x += rnd(3, -3);
        this.y += rnd(3);
    }
}

function SnowList(num) {
    this.list = new Array();
    this.length = num;
    this.show();
}

SnowList.prototype.show = function(num) {
    var length = this.list.length;
    if (length < this.length) {
        this.list[length] = new Snow();
    }
    for (var i = 0; i < length; ++i) {
        this.list[i].show();
    }
    //下面3行代码用来向setTimeout传this的函数
    //如果不想这么麻烦,直接在主程序用setInterval即可,但是不能实现每次变化的间隔时间都随机
    var _this = this;
    show = function(){ _this.show(); };
    setTimeout(show, rnd(100));
}
</script>
</head>
<body>
<div id="sky" style="position: relative; height: 300px; width:100%"></div>
<script type="text/javascript">
snowList = new SnowList(100); //写了半天,其实主程序就一句,面向对象真强大
</script>

0条评论 你不来一发么↓

    想说点什么呢?