用html5_canvas画时钟

摘要:用html5_canvas画时钟

查看示例

html代码

1
2
3
<div class="main">
<canvas id="myCanvas" width="300" height="300"></canvas>
</div>

css代码

1
2
3
4
5
6
7
8
9
10
11
<style>
body {
margin: 0;
padding: 0;
}
#myCanvas {
margin: 10px auto;
border-radius: 10px;
display: block;
}
</style>

js代码

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
<script>
var Clock = {
init: function () {
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
var r = 100;
var width = 300;
//画表盘外圆
context.clearRect(0, 0, width, width)
context.save()
context.translate(width / 2, width / 2)
context.beginPath();
context.arc(0, 0, r, 0, 2 * Math.PI, false)
context.strokeStyle = 'blue';
context.lineWidth = 1
context.stroke();
//画大、小刻度
context.rotate(3 * Math.PI / 2);//x轴正方向为上
for (var i = 0; i < 12 * 5; i++) {
context.strokeStyle = 'black'
context.beginPath()
context.moveTo(r, 0)
if (i % 5 == 0) {
context.lineTo(r - 10, 0)
} else {
context.lineTo(r - 5, 0)
}
context.stroke()
context.rotate(2 * Math.PI / 60);
}
//画指针
var now = new Date()
var hour = now.getHours();//23
hour = hour >= 12 ? hour - 12 : hour;//11
var min = now.getMinutes();//4
var sec = now.getSeconds();//30
//时针
var temp=hour*2*Math.PI/12+min*2*Math.PI/(12*60)//1小时顺时针转2pi/12弧度+1min转2pi/(12*60)
context.rotate(temp)
context.beginPath()
context.moveTo(0,0)
context.lineTo(60,0)
context.stroke()
context.rotate(2*Math.PI-temp)//恢复x轴正方向
//分针
context.rotate(min*2*Math.PI/60)//1分钟顺时针转2pi/60弧度
context.beginPath()
context.moveTo(0,0)
context.lineTo(80,0)
context.stroke()
context.rotate(2*Math.PI-min*2*Math.PI/60)
//秒针
context.rotate(sec*2*Math.PI/60)//1秒钟顺时针转2pi/60弧度
context.strokeStyle='red'
context.beginPath()
context.moveTo(-20,0)
context.lineTo(90,0)
context.stroke()
context.restore()
}

}
window.onload = function () {
setInterval(function(){
Clock.init();
},1000)
}
</script>