根据学习的资料,自己动手写代码实现桌球。代码如下:

View Code
<!DOCTYPE HTML>
<head>
 <title>撞球</title>
 <meta charset = 'utf-8'/>
</head>
<canvas id="myCanvas" width="847" height="440" style="border:1px solid gray;background-color:#000000"/>
<script type="text/javascript">
 var canvas = document.getElementById('myCanvas');
 var context = canvas.getContext("2d");
 var r = 10;
 var balls=[];
 function randomColor(){
    var arrHex=["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"];
    var strHex="#";
    var index;
    for( var i = 0;i<6;i++){
      index=Math.round(Math.random()*15);
      strHex+=arrHex[index];
    }
    return strHex;
 }
 function initBall(){
     var parentBall={
     position:{x:200,y:200},
     r:r,
     color:"#fff"
     };
     var firstBall={
     position:{x:550,y:200},
     r:r,
     color:randomColor()
     };
     
     for(var i =1;i<5;i++){
        for(var j=1;j<=i+1;j++){
         var ball={
         position:{x:firstBall.position.x+Math.sqrt(3)*r*i,y:firstBall.position.y-i*r+2*(j-1)*r},
         r:r,
         color:randomColor()
         };
         balls.push(ball);
     }
 }
 balls.push(parentBall);
 balls.push(firstBall);
 }
 function draw(){
   for(i in balls){
    context.fillStyle=balls[i].color;
    context.beginPath();
    context.arc(balls[i].position.x,balls[i].position.y,r,0,Math.PI*2,false);
    context.closePath();
    context.fill();  
  }
 }

initBall();
draw();

</script>

HTML5:练习的还是canvas的这个标签

JAVASCIRPT:javascript中对象,球是用javascript中的对象表示出来,而且利用的是json创建的对象。