Canvas模拟钟表
技术:HTML5 Canvas标签 + JS
思想:间歇定时器 + 图形绘制
技术难点:文本定位
效果图:
代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>时钟</title>
<style>
#canvas {
margin: 100px;
/* border: 1px solid #f00; */
}
</style>
</head>
<body>
<canvas id="canvas"></canvas>
</body>
<script>
const PI = Math.PI;
let canvas = document.getElementById("canvas");
canvas.width = 400;
canvas.height = 400;
let ctx = canvas.getContext("2d");
if (canvas.getContext) {
var timer = setInterval(() => {
// 每次需要重新绘制, 否则绘制的图形会叠加
ctx.clearRect(0, 0, 400, 400);
// 获取时间
var d = new Date();
var Hour = d.getHours() > 12 ? d.getHours() - 12 : d.getHours();
var Minutes = d.getMinutes();
var seconds = d.getSeconds();
ctx.save();
ctx.translate(200, 200); // 更换原点,方便计算
// 绘制外轮廓 -- 圆
ctx.beginPath();
ctx.lineWidth = 2;
ctx.moveTo(0, 0);
ctx.arc(0, 0, 196, 0, 2 * PI, false);
ctx.closePath();
ctx.stroke();
// 绘制表盘刻度
for (let i = 0; i <= 60; i++) {
ctx.beginPath();
ctx.moveTo(0, 0);
ctx.lineWidth = i % 5 === 0 ? 2 : 1; // 5 的倍数为小时 12 个刻度 ,线宽加粗
ctx.arc(0, 0, 196, ((i * 6) / 180) * PI, ((i * 6) / 180) * PI, false);
ctx.closePath();
ctx.stroke();
}
// 以白色抵消表盘内的线条,只剩下刻度线条
let r = 0;
for (let i = 0; i <= 60; i++) {
r = i % 5 === 0 ? 180 : 190;
ctx.beginPath();
ctx.lineWidth = 5;
ctx.strokeStyle = "#fff";
ctx.moveTo(0, 0);
ctx.arc(0, 0, r, ((i * 6) / 180) * PI, ((i * 6) / 180) * PI, false);
ctx.closePath();
ctx.stroke();
}
// 文本
let num = ['III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX', 'X', 'XI', 'XII', 'I', 'II'];
for (let i = 0; i < 12; i++) {
ctx.save(); // 保存原先的原点位置
// 利用正弦,余弦将对应的数字平移到相应的位置
ctx.translate(
Math.cos((30 * i / 180) * PI) * 160 - 11,
Math.sin((30 * i / 180) * PI) * 160 + 6
);
ctx.font = "20px 'Times New Roman'";
ctx.fillText(num[i], 0, 0);
ctx.restore(); // 恢复原先的原点位置
}
// 时针
ctx.strokeStyle = "#000";
ctx.lineWidth = 3;
ctx.beginPath();
ctx.moveTo(0, 0);
// 时针对应的刻度 : 需要加上对应的 分针,和秒针的比例 1小时=60分=3600秒
ctx.lineTo(
Math.cos(((Hour + Minutes / 60 + seconds / 3600) * 5 / 30) * PI - PI / 2) * 100,
Math.sin(((Hour + Minutes / 60 + seconds / 3600) * 5 / 30) * PI - PI / 2) * 100
);
ctx.stroke();
// 分针
ctx.beginPath();
ctx.lineWidth = 2;
ctx.moveTo(0, 0);
ctx.lineTo(
Math.cos(((Minutes + seconds / 60) / 30) * PI - PI / 2) * 130,
Math.sin(((Minutes + seconds / 60) / 30) * PI - PI / 2) * 130
);
ctx.stroke();
// 秒针
ctx.beginPath();
ctx.lineWidth = 1;
ctx.moveTo(0, 0);
ctx.lineTo(
Math.cos((seconds / 30) * PI - PI / 2) * 160,
Math.sin((seconds / 30) * PI - PI / 2) * 160
);
ctx.stroke();
// 圆心
ctx.beginPath();
ctx.fillStyle = '#fff'
ctx.lineWidth = 2;
ctx.arc(0, 0, 5,0,2 * PI, false);
ctx.stroke()
ctx.fill()
// logo文本
ctx.beginPath();
ctx.fillStyle = '#000'
ctx.textAlign = 'center'
ctx.font = "bold 20px 楷体";
ctx.fillText('蓝玉小轩', 0, -80);
ctx.restore();
}, 500);
} else {
alert("请升级您的浏览器版本!");
}
</script>
</html>
注意:代码的顺序影响绘制的效果,原理:代码执行的顺序会影响绘制图形的覆盖情况