跳到主要内容

canvas 时钟

clock();
setInterval(clock, 10); /// 每一秒钟重新绘制一次
function clock() {
var now = new Date(); // 得到当前日期和时间
var sec = now.getSeconds(),
min = now.getMinutes(),
hour = now.getHours();
// var ms = new Date(milliseconds); // 得到时分秒
hour = hour >= 12 ? hour - 12 : hour; // 判断小时
/* other code */
var k = now % 60000;
var ctx = document.getElementById('myCanvas').getContext('2d'); // 或取上下文对象
ctx.save(); // 保存图形状态
ctx.clearRect(0, 0, 300, 300); // 初始化画布
ctx.translate(150, 150); // 平移坐标
ctx.scale(0.4, 0.4); // 缩放效果
ctx.rotate(-Math.PI / 2); // 旋转效果
ctx.strokeStyle = '#660'; // 线条颜色
ctx.fillStyle = '#f0f'; // 填充颜色
ctx.lineWidth = 8;
ctx.lineCap = 'round';
ctx.save();
ctx.beginPath();
for (var i = 0; i < 12; i++) {
ctx.rotate(Math.PI / 6);
ctx.moveTo(300, 0);
ctx.lineTo(290, 0);
}
ctx.stroke();
ctx.restore();
ctx.save();
ctx.lineWidth = 5;
ctx.beginPath();
for (var i = 0; i < 60; i++) {
// 分钟刻度
if (i % 5 != 0) {
ctx.moveTo(296, 0);
ctx.lineTo(295, 0);
}
ctx.rotate(Math.PI / 30);
}
ctx.stroke();
ctx.restore();
ctx.save();
ctx.rotate(
(Math.PI / 6) * hour + (Math.PI / 360) * min + (Math.PI / 21600) * sec,
); // 画上时针
ctx.lineWidth = 14; // 宽度
ctx.beginPath();
ctx.moveTo(-10, 0); // 移动光标位置
ctx.lineTo(175, 0); // 绘制时针
ctx.stroke();
ctx.restore();
ctx.save();
ctx.rotate((Math.PI / 30) * min + (Math.PI / 1800) * sec); // 分针
ctx.strokeStyle = '#990099'; // 分针颜色
ctx.lineWith = 10; // 线条粗度
ctx.beginPath();
ctx.moveTo(-28, 0); // 当前光标
ctx.lineTo(262, 0); // 画线条
ctx.stroke(); // 绘制线条
ctx.restore(); // 恢复状态
ctx.save(); // 保存状态
ctx.rotate((k * Math.PI) / 30000); // 秒针
ctx.strokeStyle = '#ff0000'; // 秒针颜色
ctx.lineWidth = 1; // 线条宽度
ctx.beginPath();
ctx.moveTo(-30, 0); // 当前光标
ctx.lineTo(293, 0); // 画线条
ctx.stroke(); // 绘制线条
ctx.restore(); // 恢复状态
ctx.save(); // 保存状态
ctx.lineWidth = 14; // 线条宽度
ctx.strokeStyle = '#325FA2'; // 线条颜色
ctx.beginPath();
ctx.arc(0, 0, 350, 0, Math.PI * 2, true); // 画圆形
ctx.stroke(); // 绘制线条
ctx.restore(); // 恢复状态
ctx.restore(); // 恢复状态
}