Contents

效果图如下:

效果图

附上代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>使用Canvas绘制钟表</title>
<style>
body {
background-color: pink;
}
#clock {
display: block;
margin: auto;
margin-top: 100px;
}
</style>

<script>
window.onload = function() {
var drawing = document.getElementById("clock");
var context = drawing.getContext("2d");
function drawClock() {
context.clearRect(0, 0, drawing.width, drawing.height);

var circleX = 200; // 圆心X坐标
var circleY = 200; // 圆心Y坐标
var radius = 190; // 半径长度

// 获取时间信息
var date = new Date();
var hour = date.getHours();
var min = date.getMinutes();
var sec = date.getSeconds();

// 分针走一圈60度,时针走30度
// 度数转化为弧度 度数*Math.PI/180
var hourValue = (-90+30*hour+min/2)*Math.PI/180;
var minValue = (-90+6*min)*Math.PI/180;
var secValue = (-90+6*sec)*Math.PI/180;

// 绘制表盘
context.beginPath();
context.font = "bold 16px Arial";
context.lineWidth = '3';
for(var i=0;i<12;i++) {
context.moveTo(circleX,circleY);
context.arc(circleX,circleY,radius,30*i*Math.PI/180,30*(i+1)*Math.PI/180,false);
}
context.stroke();

context.fillStyle='#0ff';
context.beginPath();
context.moveTo(circleX,circleY);
context.arc(circleX,circleY,radius*19/20,0,360*Math.PI/180,false);
context.closePath();
context.fill();

// 绘制钟表中心
context.beginPath();
context.arc(200,200,6,0,360,false);
context.fillStyle = "#000";
context.fill();//画实心圆
context.closePath();

// 绘制时针刻度
context.lineWidth = '5';
context.beginPath();
context.moveTo(circleX, circleY);
context.arc(circleX, circleY, radius*9/20, hourValue, hourValue, false);
context.stroke();

// 绘制分针
context.lineWidth = '3';
context.beginPath();
context.moveTo(circleX, circleY);
context.arc(circleX, circleY, radius*13/20, minValue, minValue, false);
context.stroke();

// 绘制秒针
context.lineWidth = '1';
context.beginPath();
context.moveTo(circleX, circleY);
context.arc(circleX, circleY, radius*18/20, secValue, secValue, false);
context.stroke();


// 绘制钟表的数字
context.fillStyle = "#0ad";
context.fillText("12", 190, 34);
context.fillText("3", 370, 206);
context.fillText("6", 196, 378);
context.fillText("9", 22, 206);

}
setInterval(drawClock, 1000);
drawClock();
}
</script>

</head>
<body>
<canvas id="clock" width="400" height="400">
<span>你的浏览器不支持canvas元素,换个浏览器试试吧</span>
</canvas>
</body>
</html>
Contents