台球
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="Generator" content="EditPlus®">
<meta name="Author" content="">
<meta name="Keywords" content="">
<meta name="Description" content="">
<title>Document</title>
</head>
<body>
<canvas id="myCanvas" width="800" height="400" style="background-color:#000000">
Your broswer does not support the canvas element.
</canvas>
<script type="text/javascript">
var c=document.getElementById("myCanvas");
var cxt=c.getContext("2d");
var r=10;
var balls=[];
function initBall(){
var parentBall={
position:{x:200,y:150},
r:r,
color:"#fff"
};
function randomColor(){
var arrHex=["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E"];
var strHex="#";
var index;
for(var i=0;i<6;i++){
index=Math.round(Math.random()*15);
strHex+=arrHex[index];
}
return strHex;
}
var firstBall={
position:{x:400,y:150},
r:r,
color:randomColor()
}
for(var j=1;j<5;j++){
for(var k=0;k<j+1;k++){
var ball={
position:{x:firstBall.position.x+j*Math.sqrt(3)*r,y:firstBall.position.y-j*r+2*k*r},
r:r,
color:randomColor()//产生随机颜色
}
balls.push(ball);
}
}
balls.push(firstBall);
balls.push(parentBall);
}//15个小球的画法
function draw(){
for(i in balls){
cxt.fillStyle=balls[i].color;
cxt.beginPath();
cxt.arc(balls[i].position.x,balls[i].position.y,balls[i].r,0,Math.PI*2,true);
cxt.closePath();
cxt.fill();
}
}
initBall();
draw();
</script>
</body>
</html>