用JavaScript实现彩球效果

标签:JavaScript

昨天找来一个JavaScript的画图库,可以描绘大部分图形,英文文档和下载在下面
http://www.walterzorn.com/jsgraphics/jsgraphics_e.htm

然后我花了点时间写了个彩球效果的实现。
为避免某些人浏览器卡死,只设置了100个彩球。建议用Chrome浏览,Firefox会很慢,IE尚可。


实现代码如下,话说JavaScript的代码真美:
<!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">
var Color = new Array("#ff0000","#00ff00","#0000ff","#000000","#cccccc"); //颜色表

//返回随机数
function rnd(max, min) {
	if (min == undefined) {
		min = 0;
	}
	return(min + Math.floor(Math.random() * (max - min)));
}

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

Ball.prototype.init = function() {
	this.x = rnd(400); //宽400px
	this.y = 0;
	this.size = rnd(20, 4);
	this.graph.setColor(Color[rnd(Color.length)]); //随机设置颜色
}

Ball.prototype.show = function() {
    this.graph.clear();
    this.graph.fillEllipse(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 BallList(num) {
	this.list = new Array();
	this.length = num;
	this.show();
}

BallList.prototype.show = function(num) {
	var length = this.list.length;
	if (length < this.length) {
		this.list[length] = new Ball();
	}
	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">
balls = new BallList(100); //写了半天,其实主程序就一句,面向对象真强大
</script>
</body>
</html>

1条评论 你不来一发么↓ 顺序排列 倒序排列

    向下滚动可载入更多评论,或者点这里禁止自动加载

    想说点什么呢?