1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset="utf-8"> 5 <title>这是一个canvas动画</title> 6 <style media="screen"> 7 div{ 8 text-align: center; 9 margin-top: 100px; 10 } 11 #canvas{ 12 border: 1px solid #fff; 13 } 14 </style> 15 </head> 16 <body> 17 <div class=""> 18 <canvas id="canvas" width="200" height="200"></canvas> 19 </div> 20 21 <script type="text/javascript" > 22 var dom=document.getElementById("canvas"); 23 var ctx=dom.getContext('2d'); 24 var width=ctx.canvas.width; 25 var height=ctx.canvas.height; 26 var r=width/2; 27 function drawBackGround(){ 28 ctx.save(); 29 ctx.translate(r,r); 30 ctx.beginPath(); 31 ctx.lineWidth=10; 32 ctx.arc(0,0,r-5,0,2*Math.PI,false); 33 ctx.stroke(); 34 var hourMoutine=[3,4,5,6,7,8,9,10,11,12,1,2]; 35 ctx.font='16px Arial'; 36 ctx.textAlign='center'; 37 ctx.textBaseline='middle'; 38 hourMoutine.forEach(function(number,i){ 39 var rad=2*Math.PI/12*i; 40 var x=Math.cos(rad)*(r-28); 41 var y=Math.sin(rad)*(r-28); 42 ctx.fillText(number,x,y); 43 }); 44 for(var i=0;i<60;i++){ 45 var rad=2*Math.PI/60*i; 46 var x=Math.cos(rad)*(r-18); 47 var y=Math.sin(rad)*(r-18); 48 ctx.beginPath(); 49 if(i%5==0){ 50 ctx.fillStyle='#000'; 51 ctx.arc(x,y,2,0,2*Math.PI,false); 52 }else{ 53 ctx.fillStyle="#ccc"; 54 ctx.arc(x,y,2,0,2*Math.PI,false); 55 } 56 ctx.fill(); 57 } 58 } 59 function drawHour(hour,minute){ 60 ctx.save(); 61 ctx.beginPath(); 62 var rad=2*Math.PI/12*hour; 63 var mrad=2*Math.PI/12/60*minute; 64 ctx.rotate(rad+mrad); 65 ctx.lineCap='round'; 66 ctx.lineWidth=6; 67 ctx.moveTo(0,10); 68 ctx.lineTo(0,-r/2); 69 ctx.stroke(); 70 ctx.restore(); 71 } 72 function drawMinute(minute){ 73 ctx.save(); 74 ctx.beginPath(); 75 var rad=2*Math.PI/60*minute; 76 ctx.rotate(rad); 77 ctx.lineWidth=3; 78 ctx.lineCap='round'; 79 ctx.moveTo(0,10); 80 ctx.lineTo(0,-r+30); 81 ctx.stroke(); 82 ctx.restore(); 83 } 84 function drawSecond(second){ 85 ctx.save(); 86 ctx.beginPath(); 87 ctx.fillStyle='#E05444'; 88 var rad=2*Math.PI/60*second; 89 ctx.rotate(rad); 90 ctx.moveTo(-2,20); 91 ctx.lineTo(2,20); 92 ctx.lineTo(1,-r+18); 93 ctx.lineTo(-1,-r+18); 94 ctx.fill(); 95 ctx.restore(); 96 } 97 function dwawDot(){ 98 ctx.beginPath(); 99 ctx.fillStyle="#fff"; 100 ctx.arc(0,0,3,0,2*Math.PI,false); 101 ctx.fill(); 102 } 103 104 function draw(){ 105 ctx.clearRect(0,0,width,height); 106 var now=new Date(); 107 var hour=now.getHours(); 108 var minute=now.getMinutes(); 109 var second=now.getSeconds(); 110 drawBackGround(); 111 drawHour(hour,minute); 112 drawMinute(minute); 113 drawSecond(second); 114 dwawDot(); 115 ctx.restore(); 116 } 117 setInterval(draw,1000); 118 119 </script> 120 </body> 121 </html>