html5-canvas绘制时钟
2014-07-17 00:21 肖十一 阅读(343) 评论(0) 收藏 举报使用HTML5 canvas绘制时钟,废话不多说,下面是具体的JS部分代码

1 <script> 2 var boxObj=document.getElementById("box"); 3 var ctx=boxObj.getContext("2d"); 4 //控制指针长度变量 5 var clockRadius=250; 6 7 window.onload=function(){ 8 setInterval(drawClock,1000); 9 10 } 11 function drawClock(){ 12 ctx.clearRect(0,0,1200,1000); 13 var date=new Date(); 14 var hours=date.getHours(); 15 var minutes=date.getMinutes(); 16 var seconds=date.getSeconds(); 17 hours=hours>12?hours-12:hours; 18 var hour=hours+minutes/60; 19 var minute=minutes+seconds/60; 20 21 ctx.beginPath(); 22 ctx.lineWidth = 3; 23 ctx.fillStyle="#eee" 24 ctx.strokeStyle="#000" 25 ctx.arc(620,500,320,0,360*Math.PI/180); 26 ctx.closePath(); 27 ctx.stroke(); 28 ctx.fill() 29 30 31 for(var i = 0; i<12; i++){ 32 ctx.save(); 33 ctx.beginPath(); 34 ctx.lineWidth = 3; 35 ctx.translate(620,500); 36 ctx.rotate(i*30*Math.PI/180); 37 ctx.moveTo(280,0); 38 ctx.lineTo(300,0); 39 ctx.closePath(); 40 ctx.stroke(); 41 ctx.restore(); 42 } 43 for(var i = 0; i<60; i++){ 44 ctx.save(); 45 ctx.beginPath(); 46 ctx.lineWidth = 1; 47 ctx.translate(620,500); 48 ctx.rotate(i*6*Math.PI/180); 49 ctx.moveTo(295,0); 50 ctx.lineTo(300,0); 51 ctx.closePath(); 52 ctx.stroke(); 53 ctx.restore(); 54 } 55 //时针 56 ctx.save(); 57 ctx.translate(620,500); 58 ctx.rotate((hour-3)*2*Math.PI/12); 59 ctx.beginPath(); 60 ctx.moveTo(-15,-5); 61 ctx.lineTo(-15,5); 62 ctx.lineTo(clockRadius*0.5,1); 63 ctx.lineTo(clockRadius*0.5,-1); 64 ctx.fillStyle="#000"; 65 ctx.closePath(); 66 ctx.fill(); 67 ctx.restore(); 68 //分针 69 ctx.save(); 70 ctx.translate(620,500); 71 ctx.rotate((minute-15)*2*Math.PI/60); 72 ctx.beginPath(); 73 ctx.moveTo(-15,-4); 74 ctx.lineTo(-15,4); 75 ctx.lineTo(clockRadius*0.7,1); 76 ctx.lineTo(clockRadius*0.7,-1); 77 ctx.fillStyle="#000"; 78 ctx.closePath(); 79 ctx.fill(); 80 ctx.restore(); 81 //秒针 82 ctx.save(); 83 ctx.translate(620,500); 84 ctx.rotate((seconds-15)*2*Math.PI/60); 85 ctx.beginPath(); 86 ctx.moveTo(-15,-3); 87 ctx.lineTo(-15,3); 88 ctx.lineTo(clockRadius*1.1,1); 89 ctx.lineTo(clockRadius*1.1,-1); 90 ctx.fillStyle="#f00"; 91 ctx.closePath(); 92 ctx.fill(); 93 ctx.restore(); 94 ctx.restore(); 95 } 96 97 98 99 </script>
浙公网安备 33010602011771号