SOURCE

console 命令行工具 X clear

                    
>
console
/**
 * [canvas code Study description]
 * @date : 2013-08-16
 * canvas的宽高写在自己的属性里比较好
 */
var BounceBall = function (){
	var ctx,W,H,
		x = 100,
		y = 10,
		mx = 3,
		my = 5,
		bw = 100,
		bh = 5,
		offx = 0,
		isL = false,
		isR = false;
	var init = function(id){
		var obj = document.getElementById(id);
		ctx = obj.getContext('2d');
		W = obj.width || 800 ;
		H = obj.height || 600 ;
		offx = (W - bw)/2;
		this.timer = null;
		this.run();
	}
	init.prototype = {
		run : function(){
			var that = this;
			clearTimeout(this.timer);
			this.timer = setTimeout(function(){
				that.run();
				that.draw();
			},20);
			this.evListener();
		},
		random : function(m,n){
			return Math.floor(Math.random*m + 1) - n;
		},
		draw : function(){
			// 清除重绘
			this.clear();
			// 重绘小球
			this.circle(x,y,8);
			// 重绘滑板
			this.board(offx);
			// 碰撞检测
			(x + mx > W || x + mx < 0) && (mx = -mx);
			y + my < 0 && (my = -my);
			if(y + my > H - bh){
				x >= offx && x <= offx + bw ? my = -my : this.stop();
			}
			x += mx;
			y += my;
			// 挡板偏移
			isL && (offx - 10 >= 0) && (offx -= 10);
			isR && (offx + 10 <= W - bw) && (offx += 10);
		},
		// 清除所有
		clear : function(){
			ctx.clearRect(0,0,W,H);
		},
		// 画圆
		circle : function(x,y,r){
			ctx.beginPath();
			ctx.arc(x,y,r,0,2*Math.PI,true);
			ctx.closePath();
			ctx.fill();
		},
		// 画矩形
		rect : function(x,y,w,h){
			ctx.beginPath();
			ctx.rect(x,y,w,h);
			ctx.closePath();
			ctx.fill();
		},
		// 画挡板
		board : function(fx){
			this.rect(fx,H - bh,bw,bh);
		},
		// 左右键注册事件 判断滑板状态
		evListener : function(){
			document.addEventListener('keydown',function(e){
				e.keyCode == 37 && (isL = true);
				e.keyCode == 39 && (isR = true);
			},false);

			document.addEventListener('keyup',function(e){
				e.keyCode == 37 && (isL = false);
				e.keyCode == 39 && (isR = false);
			},false);
		},
		stop : function(){
			clearTimeout(this.timer);
			this.timer = null;
			alert('Game Over');
		}
	}
	return init;
}();
window.onload = function(){
	new BounceBall('demo');
}
<canvas id="demo" width='800' height='600'>
	哎哟~太out啦!居然用不支持canvas的浏览器
</canvas>
canvas{
	display:block;
	margin-left: auto;
	margin-right: auto;
}
#demo{
	margin-top: 20px;
	border:2px solid #ccc;
}