javascript - Canvas 时钟应从特定位置开始

标签 javascript html css

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

最佳答案

我已将您的代码更改为使用任意时间和日期。通过 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);

关于javascript - Canvas 时钟应从特定位置开始,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38582427/

相关文章:

javascript - 如何使用Javascript在函数内部调用外部库的函数?

html - 解决带有图像的 HTML 表格中的溢出

jquery - 使用 Bootstrap 进行绝对定位

html - 使用 Bootstrap ,包含较大的图像以放置在较小的静态 div 中

html - 我怎样才能让我的网站内容在我的固定菜单栏下滚动并在透明背景下消失?

asp.net - 链接页面的弹出缩略图

javascript - 等待来自链式 sequelize 函数的异步响应

javascript - 需要从启用多选的 html 文件输入中删除特定文件

css - 缩进文本区域内的所有行

javascript - 在 React 中使用 immutability-helper 设置可变对象键