通过学习canvas的内容绘制了一个时钟demo,效果如下
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>clock</title>
</head>
<body>
<canvas width="500" height="500" id="canvas"></canvas>
<script>
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
function drawClock() {
//获取当前的时分秒
var now = new Date();
var seconds = now.getSeconds();
var minute = now.getMinutes();
var hour = now.getHours();
//小时分钟必须获取浮点类型
minute = minute + seconds / 60;
hour = hour + minute / 60;
//将24小时转换为12小时
hour = hour > 12 ? hour - 12 : hour;
//画圆
ctx.beginPath();
ctx.lineWidth = 8;
ctx.arc(250, 250, 200, 0, 2 * Math.PI, false);
ctx.strokeStyle = '#000';
ctx.stroke();
//画时钟的刻度 12个刻度,每个刻度旋转30度
for (var i = 0; i <= 12; i++) {
ctx.save();
ctx.strokeStyle = '#A9A9A9';
ctx.lineWidth = 6;
ctx.translate(250, 250); //设置画布的原点
ctx.rotate(30 * Math.PI / 180 * i);
ctx.beginPath();
ctx.moveTo(0, -172);
ctx.lineTo(0, -195);
ctx.stroke();
ctx.restore();
}
//画秒钟的刻度 60个刻度,每个刻度旋转6度
for (var i = 0; i <= 60; i++) {
ctx.save();
ctx.strokeStyle = '#A9A9A9';
ctx.lineWidth = 3;
ctx.translate(250, 250); //设置画布的原点
ctx.rotate(6 * Math.PI / 180 * i, 300, 300);
ctx.beginPath();
ctx.moveTo(0, -182);
ctx.lineTo(0, -195);
ctx.stroke();
ctx.restore();
}
//标注小时
ctx.fillStyle = '#000';
ctx.font = '22px 微软雅黑';
ctx.lineWidth = 3;
ctx.fillText(12, 236, 100);
ctx.fillText(1, 320, 120);
ctx.fillText(2, 380, 170);
ctx.fillText(3, 406, 260);
ctx.fillText(4, 380, 340);
ctx.fillText(5, 325, 395);
ctx.fillText(6, 245, 418);
ctx.fillText(7, 165, 396);
ctx.fillText(8, 108, 340);
ctx.fillText(9, 82, 260);
ctx.fillText(10, 106, 180);
ctx.fillText(11, 160, 126);
//画时针
ctx.save();
ctx.lineWidth = 4;
ctx.strokeStyle = '#000';
ctx.translate(250, 250);
ctx.rotate(hour * 30 * Math.PI / 180);
ctx.beginPath();
ctx.moveTo(0, 20);
ctx.lineTo(0, -100);
ctx.stroke();
ctx.restore();
//画分针
ctx.save();
ctx.lineWidth = 3;
ctx.strokeStyle = '#000';
ctx.translate(250, 250);
ctx.rotate(minute * 6 * Math.PI / 180);
ctx.beginPath();
ctx.moveTo(0, 25);
ctx.lineTo(0, -130);
ctx.stroke();
ctx.closePath();
ctx.restore();
//画秒针
ctx.save();
ctx.lineWidth = 2;
ctx.strokeStyle = '#000';
ctx.translate(250, 250);
ctx.rotate(seconds * 6 * Math.PI / 180);
ctx.beginPath();
ctx.moveTo(0, 30);
ctx.lineTo(0, -140);
ctx.stroke();
ctx.closePath();
ctx.restore();
// 画圆心
ctx.beginPath();
ctx.arc(250, 250, 5, 0, Math.PI * 2, true);
ctx.closePath();
ctx.fillStyle = "red";
ctx.fill();
setTimeout(function() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawClock();
}, 1000)
}
drawClock();
setInterval(drawClock, 1000);
</script>
</body>
</html>