画布时钟应从特定位置

时间:2016-07-26 06:25:15

标签: javascript html5 css3

我想从特定位置启动时钟的秒针,例如加载页面时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();
  }

1 个答案:

答案 0 :(得分: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);