console
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;
}