canvas-clock

by bingqichen

HTML

<script src="//cdn.bootcss.com/moment.js/2.21.0/moment.min.js"></script>
<script src="//cdn.bootcss.com/moment.js/2.21.0/locale/zh-cn.js"></script>
<div class="wrap">
  <canvas id="canvas" width="400" height="400"></canvas>
</div>

CSS

* {
  padding: 0;
  margin: 0;
  box-sizing: border-box;
  outline: none;
  border: none;
}

JavaScript

moment.locale('zh-cn');
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');

function draw() {
  ctx.resetTransform(); // 重新绘图前清除变换效果
  ctx.clearRect(0, 0, 300, 300); // 清除内容

  const now = moment();

  ctx.strokeStyle = 'black';
  ctx.strokeRect(0, 0, 300, 300);

  ctx.translate(150, 150); // 移动坐标系中心点

  // 绘制黑色底盘
  ctx.beginPath();
  ctx.moveTo(-100, -80);
  ctx.quadraticCurveTo(-100, -100, -80, -100);
  ctx.lineTo(80, -100);
  ctx.quadraticCurveTo(100, -100, 100, -80);
  ctx.lineTo(100, 80)
  ctx.quadraticCurveTo(100, 100, 80, 100);
  ctx.lineTo(-80, 100);
  ctx.quadraticCurveTo(-100, 100, -100, 80);
  ctx.fillStyle = 'black';
  ctx.fill();

  // 绘制日期文字
  ctx.textAlign = 'left';
  ctx.fillStyle = '#ce4c50';
  ctx.font = '11px "Helvetica Neue"';
  ctx.textBaseline = 'middle';
  ctx.fillText(now.format('D'), 15, 0);
  ctx.fillStyle = 'white';
  ctx.fillText(now.format('ddd'), 33, 0);

  ctx.fillStyle = 'white';
  ctx.font = '20px "Helvetica Neue"';
  ctx.strokeStyle = 'white';
  ctx.textAlign = 'center';

  // 绘制圆盘刻度点和数字
  for (let index = 60; index > 0; index -= 1) {
    if (index % 5 === 0) {
      ctx.lineWidth = 3
      ctx.fillText(index / 5, 0, -70);
    } else {
      ctx.lineWidth = 1;
    }
    ctx.beginPath();
    ctx.moveTo(0, -90);
    ctx.lineTo(0, -85);
    ctx.stroke();
    ctx.rotate(-Math.PI * 2 * (1 / 60));
  }

  const h = now.format('h');
  const m = now.format('m');
  const s = now.format('s');
  const ms = now.format('SSS');

  // 时针
  const hour = new Path2D();
  hour.arc(0, 0, 2, 0, Math.PI * 2);

  // hour.moveTo(-2, 0);
  // hour.bezierCurveTo(-2, -2, 0, -1, -1, -12);
  hour.moveTo(-1, -1);
  hour.lineTo(-1, -12)

  hour.lineTo(-2, -13);
  hour.lineTo(-2, -45);
  hour.arc(0, -47, 2, -Math.PI, 0);
  hour.lineTo(2, -13);

  // hour.lineTo(1, -12);
  // hour.bezierCurveTo(0, 1, 2, -2, 2, 0);
  hour.lineTo(1, -12);
  hour.lineTo(1, -1);

  // 分针
  const minute = new Path2D();
  minute.arc(0, 0, 2, 0,...