用canvas和js畫了個鐘錶,跟大家分享一下
<pre name="code" class="javascript">(function () { var mycanvas=document.getElementById("mycanvas"); var otex=mycanvas.getContext("2d"); function time() { otex.clearRect(0,0,500,500); //畫大圓 otex.beginPath(); otex.arc(250,250,200,0,2*Math.PI); otex.strokeStyle="#abcdef"; otex.lineWidth=10; otex.closePath(); otex.stroke(); //秒針 otex.strokeStyle="grey"; otex.lineWidth=5; for(var i=0;i<60;i++){ otex.save(); otex.beginPath(); otex.translate(250,250); otex.rotate(i*6*Math.PI/180); otex.moveTo(0,-195); otex.lineTo(0,-180); otex.closePath(); otex.stroke(); otex.restore(); } //畫時針針 otex.strokeStyle="blue"; otex.lineWidth=10; for(var i=0;i<12;i++){ otex.save();//記得使用 otex.beginPath(); otex.translate(250,250); otex.rotate(i*30*Math.PI/180); otex.moveTo(0,-175); otex.lineTo(0,-195); otex.closePath(); otex.stroke(); otex.restore();//記得使用 } var now=new Date(); var h=now.getHours(); var m=now.getMinutes(); var s=now.getSeconds(); //計算小時 otex.save();//記得使用 otex.beginPath(); otex.strokeStyle="blue"; otex.lineWidth=5; otex.translate(250,250); otex.rotate((h+m/60)*30*Math.PI/180); otex.moveTo(0,10); otex.lineTo(0,-125); otex.closePath(); otex.stroke(); otex.restore();//記得使用 //分 otex.save();//記得使用 otex.beginPath(); otex.strokeStyle="red"; otex.lineWidth=4; otex.translate(250,250); otex.rotate((m+s/60)*6*Math.PI/180); otex.moveTo(0,10); otex.lineTo(0,-165); otex.closePath(); otex.stroke(); otex.restore();//記得使用 //秒 otex.save();//記得使用 otex.beginPath(); otex.strokeStyle="red"; otex.lineWidth=4; otex.translate(250,250); otex.rotate(s*6*Math.PI/180); otex.moveTo(0,10); otex.lineTo(0,-185); otex.closePath(); otex.stroke(); otex.restore();//記得使用 } time(); setInterval(time,1000) })();
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>鐘錶</title></head><style> *{margin: 0;padding: 0;}</style><body> <canvas id="mycanvas" width="500" height="600" style=" position: relative;left:0;right:0;margin:0 auto"> </canvas><script src="main.js"></script></body>