2016-07-26 64 views
0

我想在裝載頁面時從特定位置(例如15小時)開始時鐘的秒針。畫布時鐘應該從特定位置開始

function drawTime(ctx, radius){ 
 
    now = new Date(); 
 
    second = now.getSeconds(); 
 
    second=(second*Math.PI/30); 
 
    console.log(second); 
 
    drawHand(ctx, second, radius*0.9, radius*0.02); 
 
    } 
 

 
function drawHand(ctx, pos, length, width) { 
 
    ctx.beginPath(); 
 
    ctx.lineWidth = width; 
 
    ctx.lineCap = "round"; 
 
    ctx.moveTo(0,0); 
 
    ctx.rotate(pos); 
 
    ctx.lineTo(0, -(3*length/4)); 
 
    ctx.stroke(); 
 
    ctx.rotate(-pos); 
 
    ctx.restore(); 
 
    }

回答

0

我已經改變了你的代碼使用任意時間和日期。時間的推移通過setInterval()函數來模擬。

我添加了一些評論,以便更容易理解發生了什麼。

// The starting date. The date is arbitrary, the time is set to 15:00:00. 
// .getTime() returns time in milliseconds, so it's easier to increment later on. 
var currentTime = (new Date('2011-10-10T15:00:00')).getTime(); 

function drawTime(ctx, radius){ 
    var now = new Date(currentTime); 
    var second = now.getSeconds(); 
    second = (second * Math.PI/30); 
    console.log(second); 
    drawHand(ctx, second, radius * 0.9, radius * 0.02); 
} 

function drawHand(ctx, pos, length, width) { 
    ctx.beginPath(); 
    ctx.lineWidth = width; 
    ctx.lineCap = "round"; 
    ctx.moveTo(0,0); 
    ctx.rotate(pos); 
    ctx.lineTo(0, -(3*length/4)); 
    ctx.stroke(); 
    ctx.rotate(-pos); 
    ctx.restore(); 
} 

// Emulating the clock. 1000 milliseconds = 1 second. 
setInterval(function() { 
    currentTime += 1000; 
}, 1000); 
+0

感謝維克多, 但是,當我設置時/分/秒的手中,他們不動......他們保持不變.. – Anuroop

+0

當我用now.setSeconds(15),後置當我使用now.getSeconds()時,我只得到15個輸出。第二個值不會遞增。我需要的是每秒遞增的第二個值,當我使用now.getSeconds()時,我應該將輸出作爲遞增值輸出。 – Anuroop

+0

嗯,我沒有想到這一點。也許我們可以使用'setInterval'模擬一個時鐘?我將很快通過一個例子更新我的答案 –