SVG模拟时钟

1. 直接上代码

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
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title></title>
<style>
* {
margin: 0;
}
</style>
</head>
<body>
<svg width="400" height="400">
<title>SVG Analog Clock</title>
<circle id="face" cx="125" cy="125" r="100"
style="fill: #f1f1f1; stroke: #000;"></circle>
<g id="ticks" transform="translate(125, 125)">
<path id="triangle" d="M95 0 L 100 -5 L 100 5 Z"
transform="rotate(360)"></path>
</g>
<g id="hands">
<path id="hour" d="M 125 125 V 75"
style="fill: none; stroke: black; stroke-width: 6"
transform="rotate(0)"></path>
<path id="minute" d="M 125 125 V 50"
style="fill: none; stroke: black; stroke-width: 4"
transform="rotate(0)"></path>
<path id="second" d="M 125 125 Q 100 100 125 80 T 125 40 V 30"
style="fill: none; stroke: #f00; stroke-width: 2"
transform="rotate(0)"></path>
</g>
<g id="knob" transform="translate(125, 125)">
<circle cx="0" cy="0" r="6" style="fill: #333;"></circle>
</g>
</svg>
<script>
var svgns = "http://www.w3.org/2000/svg";
var face = document.getElementById("face"),
ticks = document.getElementById("ticks"),
triangle = document.getElementById("triangle"),
txt = document.getElementById("txt");
for (var i = 0; i < 11; i++) {
var temp_triangle = triangle.cloneNode(true);
var angle = i * 30 + 30;
temp_triangle.setAttribute("transform", "rotate(" + angle + ")");
ticks.appendChild(temp_triangle);
ticks.setAttribute("transform", "translate(125, 125), rotate(-90)");
}
var hourHand = document.getElementById("hour"),
minuteHand = document.getElementById("minute"),
secondHand = document.getElementById("second");
var hourTransform, minuteTransform, secondTransform;
var secPer12Hours = 60 * 60 * 12,
secPerHour = 60 * 60,
secPerMinute = 60;
(function init() {
hourTransform = hourHand.transform.baseVal.getItem(0);
minuteTransform = minuteHand.transform.baseVal.getItem(0);
secondTransform = secondHand.transform.baseVal.getItem(0);
updateClock();
})()
function updateClock() {
var date = new Date();
var sec = date.getMilliseconds() / 1000 +
date.getSeconds() +
date.getMinutes() * 60 +
date.getHours() * 60 * 60;
var hourAngle = (sec % secPer12Hours) * 360 / secPer12Hours,
minuteAngle = (sec % secPerHour) * 360 / secPerHour,
secondAngle = (sec % secPerMinute) * 360 / secPerMinute;
hourTransform.setRotate(hourAngle, 125, 125);
minuteTransform.setRotate(minuteAngle, 125, 125);
secondTransform.setRotate(secondAngle, 125, 125);
window.requestAnimationFrame(updateClock);
}
</script>
</body>
</html>

说明

浏览器需要支持:requestAnimationFrame
有关requestAnimationFrame的相关知识请自行查阅

坚持原创技术分享,您的支持将鼓励我继续创作!