返回

轻松创建动态 Canvas 时钟:一步步打造个性时钟

前端

利用 HTML5 Canvas 的强大功能,您可以轻松制作一个动态时钟,为您的网站或应用程序增添一抹互动色彩。本文将指导您一步步创建自己的 Canvas 时钟表盘,让时间以一种引人入胜且独特的形式呈现。

步骤 1:创建画布和上下文

var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");

步骤 2:绘制时钟表盘

ctx.beginPath();
ctx.arc(canvas.width / 2, canvas.height / 2, canvas.width / 2 - 10, 0, 2 * Math.PI);
ctx.strokeStyle = "#000000";
ctx.lineWidth = 5;
ctx.stroke();

步骤 3:绘制刻度线

for (var i = 0; i < 12; i++) {
  var angle = i * (2 * Math.PI / 12);
  var x = canvas.width / 2 + (canvas.width / 2 - 10) * Math.cos(angle);
  var y = canvas.height / 2 + (canvas.width / 2 - 10) * Math.sin(angle);
  ctx.beginPath();
  ctx.moveTo(x, y);
  ctx.lineTo(x + 20 * Math.cos(angle), y + 20 * Math.sin(angle));
  ctx.strokeStyle = "#000000";
  ctx.lineWidth = 2;
  ctx.stroke();
}

步骤 4:绘制时针、分针和秒针

function drawHands() {
  var date = new Date();
  var hours = date.getHours() % 12;
  var minutes = date.getMinutes();
  var seconds = date.getSeconds();

  ctx.save();
  ctx.translate(canvas.width / 2, canvas.height / 2);
  ctx.rotate(-(hours + minutes / 60 + seconds / 3600) * 2 * Math.PI / 12);
  ctx.beginPath();
  ctx.moveTo(0, 0);
  ctx.lineTo(100, 0);
  ctx.strokeStyle = "#000000";
  ctx.lineWidth = 5;
  ctx.stroke();
  ctx.restore();

  ctx.save();
  ctx.translate(canvas.width / 2, canvas.height / 2);
  ctx.rotate(-(minutes + seconds / 60) * 2 * Math.PI / 60);
  ctx.beginPath();
  ctx.moveTo(0, 0);
  ctx.lineTo(120, 0);
  ctx.strokeStyle = "#000000";
  ctx.lineWidth = 3;
  ctx.stroke();
  ctx.restore();

  ctx.save();
  ctx.translate(canvas.width / 2, canvas.height / 2);
  ctx.rotate(-seconds * 2 * Math.PI / 60);
  ctx.beginPath();
  ctx.moveTo(0, 0);
  ctx.lineTo(140, 0);
  ctx.strokeStyle = "#FF0000";
  ctx.lineWidth = 1;
  ctx.stroke();
  ctx.restore();
}

步骤 5:创建动画循环

function animate() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  drawHands();
  requestAnimationFrame(animate);
}
animate();

通过遵循这些步骤,您将能够在 HTML5 Canvas 上创建自己的动态时钟。通过调整样式和颜色,您可以自定义时钟的外观,使其与您的网站或应用程序的风格相匹配。