標籤:style blog http color java os io for
HTML:
1 <html> 2 <head> 3 <title>canvas畫圓</title> 4 <meta http-equiv="content-type" content="text/html" charset="utf-8"> 5 <link rel="stylesheet" href="circle.css"/> 6 </head> 7 <body> 8 <canvas width="1000" height="800">你的瀏覽器不支援canvas</canvas> 9 <script type="text/javascript" src="circle.js"></script>10 </body>11 </html>
JS:
1 var a=0,//確定圖形的旋轉角度變數 2 count= 0,//確定圓的個數 3 colors=[];//儲存第一次畫的圓的顏色 4 (function drawCircle(){ 5 var canvas=document.getElementsByTagName("canvas")[0]; 6 if(canvas.getContext){ 7 //瀏覽器有getContext方法的話擷取2d上下文 8 var ctx=canvas.getContext("2d"); 9 ctx.save();//儲存一下初始的畫布狀態10 ctx.beginPath();//開始畫線11 ctx.translate(500,400);//將畫圖的原點移動到畫布中間12 ctx.rotate(30*a*Math.PI/180);//每個圓之間間隔30度13 ctx.fillStyle="rgb("+parseInt(Math.random()*256)+","+parseInt(Math.random()*256)14 +","+parseInt(Math.random()*256)+")";//隨機顏色15 colors.push(ctx.fillStyle);//儲存顏色值16 ctx.arc(40+10*a,0,5+2*a,0,Math.PI*2,true);//畫圓,每個圓的大小依次增大17 ctx.closePath();//結束畫線18 ctx.fill();//填充19 ctx.restore();//恢複到save的狀態20 }21 count++;22 a++;23 var circle1=setTimeout(drawCircle,100);24 if(count===15){25 clearTimeout(circle1);//共畫7個圓26 var b=0;27 (function circleMove(){28 ctx.clearRect(0,0,1000,800);//清除畫布29 for(var i=b;i<b+15;i++){30 ctx.save();31 ctx.beginPath();32 ctx.translate(500,400);33 ctx.rotate(30*i*Math.PI/180);34 ctx.arc(40+10*(i-b),0,5+2*(i-b),0,Math.PI*2,true);35 ctx.fillStyle=colors[i-b];36 ctx.closePath();37 ctx.fill();38 ctx.restore();39 }40 b++;41 var circle2=setTimeout(circleMove,100);42 if(b===12){43 b=0;44 }45 }());46 }47 }());