基本思路,先画一个200半径的圆
ctx.arc(250,250,200,0,2*Math.PI);
然后再画时分刻度,可以先利用translate变化坐标到圆的中心点,然后再通过rotate旋转
1 //画12个时刻度线 2 for(var i=0;i<12;i++){ 3 ctx.save(); 4 ctx.translate(250,250); 5 ctx.rotate(i*Math.PI/6); 6 ctx.moveTo(0,-180); 7 ctx.lineTo(0,-195); 8 ctx.stroke(); 9 ctx.restore(); 10 } 11 //画60个分刻度线 12 for(var i=0;i<60;i++){ 13 //经过时刻度跳过 14 if(i%5!=0){ 15 ctx.save(); 16 ctx.translate(250,250); 17 ctx.rotate(i*Math.PI/30); 18 ctx.beginPath(); 19 ctx.strokeStyle="#555"; 20 ctx.moveTo(0,-190); 21 ctx.lineTo(0,-195); 22 ctx.closePath(); 23 ctx.stroke(); 24 ctx.restore(); 25 } 26 }
需要注意,在画刻度线时要用到save()和restore()
save()是保存原始的坐标,经过变换坐标后画刻度线,再restore()回到原始坐标。不然的话,每一次坐标变化都是基于前一次的坐标。
再利用date()函数获取当前时间,得到时/分/秒,分别计算指针的相应角度,利用rotate旋转。
一开始用Math计算各指针的两端坐标,再画指针,发现需要考虑落在各象限的正负值,很烦,直接rotate旋转,太简单了。
画时针
//画时针
ctx.save();
ctx.translate(250,250);
ctx.rotate(hour/12*2*Math.PI);
ctx.beginPath();
ctx.moveTo(0,15);
ctx.lineTo(0,-150);
ctx.closePath();
ctx.stroke();
ctx.restore();
完整代码
<html> <head> <title>canvas demo</title> </head> <body> <canvas id="mycanvas" width="500px" height="500px" ></canvas> <script type="text/javascript"> drawclock(); setInterval(drawclock,1000); function drawclock(){ var mycanvas = document.getElementById("mycanvas"); var ctx = mycanvas.getContext("2d"); ctx.clearRect(0,0,500,500); //画圆圈 ctx.beginPath(); ctx.lineWidth=5; ctx.beginPath(); ctx.arc(250,250,200,0,2*Math.PI); ctx.closePath(); ctx.stroke(); ctx.beginPath(); ctx.arc(250,250,5,0,2*Math.PI); ctx.closePath(); ctx.stroke(); //画12个时度线 for(var i=0;i<12;i++){ ctx.save(); ctx.translate(250,250); ctx.rotate(i*Math.PI/6); ctx.beginPath(); ctx.moveTo(0,-180); ctx.lineTo(0,-195); ctx.closePath(); ctx.stroke(); ctx.restore(); } //画60个分度线 for(var i=0;i<60;i++){ //经过时度跳过 if(i%5!=0){ ctx.save(); ctx.translate(250,250); ctx.rotate(i*Math.PI/30); ctx.beginPath(); ctx.strokeStyle="#555"; ctx.moveTo(0,-190); ctx.lineTo(0,-195); ctx.closePath(); //context.globalCompositeOperation='xor'; ctx.stroke(); ctx.restore(); } } var now = new Date(); var sec = now.getSeconds(); var min = now.getMinutes(); var hour = now.getHours(); hour=hour>12?hour-12:hour; hour=hour+min/60; //画时针 ctx.save(); ctx.translate(250,250); ctx.rotate(hour/12*2*Math.PI); ctx.beginPath(); ctx.moveTo(0,15); ctx.lineTo(0,-150); ctx.closePath(); ctx.stroke(); ctx.restore(); //画分针 ctx.save(); ctx.translate(250,250); ctx.rotate(min/60*2*Math.PI); ctx.lineWidth=3; ctx.beginPath(); ctx.moveTo(0,20); ctx.lineTo(0,-170); ctx.closePath(); ctx.stroke(); ctx.restore(); //画分针 ctx.save(); ctx.translate(250,250); ctx.rotate(sec/60*2*Math.PI); ctx.lineWidth=1; ctx.beginPath(); ctx.moveTo(0,25); ctx.lineTo(0,-180); ctx.closePath(); ctx.stroke(); ctx.restore(); } </script> <style> #mycanvas{ border: solid 1px; } </style> </body> </html>