此時針是以畫布的中心爲圓心;javascript
g.translate(width/2,width/2);css
此函數是將畫布的原點移到(width/2,width/2)html
繪製錶盤
function jiang(){ r = width/2 g.clearRect(0, 0, 600, 600); g.save(); g.translate(r, r); g.rotate(-Math.PI / 2); //分鐘刻度線 for(var i = 0; i < 60; i++) {//畫60個刻度線 g.beginPath(); g.strokeStyle ="white"; g.lineWidth = 4; g.moveTo(250, 0); g.lineTo(240, 0); g.stroke(); g.rotate(Math.PI / 30); //每一個6deg畫一個時鐘刻度線 g.closePath(); } //時鐘刻度線 for(var i = 0; i < 12; i++) {//畫12個刻度線 g.beginPath(); g.strokeStyle ="white"; g.lineWidth = 8; g.moveTo(250, 0); g.lineTo(230, 0); g.stroke(); g.rotate(Math.PI / 6); //每一個30deg畫一個時鐘刻度 g.closePath(); } }
時針
save和restore必不可少,在這兩個函數之間,改變位置不會影響到其餘函數,在此段代碼中特指rotate,若是沒有rotate,能夠不用save和restorejava
必定要加beginPath,省得被其餘函數影響canvas
時針和分針秒針不同,一個30°,還有分針的移動會影響時針的位置函數
時針運動的原理是畫好一條線,而後旋轉那條線post
function drawHour(hour,minu){
g.save();
g.beginPath();
g.lineWidth = 9; var rad = Math.PI*2/12*hour; var radMinu = Math.PI*2/12/60*minu; g.rotate(rad + radMinu) g.moveTo(-10,0); g.lineTo(r/2,0); g.strokeStyle = "white"; g.stroke(); g.restore(); }
分針
function drawMinu(minu){ g.save(); g.beginPath(); g.lineWidth = 6; var radMinu = Math.PI*2/60*minu; g.rotate(radMinu) g.moveTo(-16,0); g.lineTo(r-100,0); g.strokeStyle = "white"; g.stroke(); g.restore(); }
秒針
function drawSeco(seco){
g.save();
g.beginPath();
g.lineWidth = 3; var radSeco = Math.PI*2/60*seco; g.rotate(radSeco) g.moveTo(-25,0); g.lineTo(r-80,0); g.strokeStyle = "#ff0032"; g.stroke(); g.restore(); }
數字表
function drawNumClock(){
var data = new Date(); var sec = data.getSeconds(); var min = data.getMinutes(); var hour = data.getHours(); g.fillStyle = "white"; g.font = "20px '楷體'"; g.beginPath(); g.rotate(Math.PI/2) g.fillText(hour,60,0); g.fillText(":",80,0); g.fillText(min,90,0); g.font = "20px '楷體'"; g.fillText(sec,120,0); }