深夜,用canvas画一个时钟

查看demo

这几天准备阿里巴巴的笔试,可以说已经是心力交瘁,自从阿里和蘑菇街的内推被刷掉之后,开始越来越怀疑起自己的能力来,虽然这点打击应该是微不足道的。毕竟校招在刚刚开始拉开帷幕,精彩的还在后头,内推不过,还有机会去秋招,这次秋招不过,还有明年的春招。但是明年的春招我可能等不起了,我迫不及待地需要一份工作,需要一份我向往的工作。

今天看书看到canvas部分,便用它来写了一个时钟,原理很简单,用context.arc(100, 100, 99, 0, Math.PI*2, false);绘制圆形作为表盘,context.fillText(i, textX, textY);绘制表盘上的数字,context.lineTo(secondsX, secondsY);绘制秒针,时针和分针的原理与此相同。接着就是正弦和余弦函数的运用。

开代码:

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
104
105
106
107
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>canvas时钟</title>
</head>
<body>
<canvas id="drawing" width="400" height="400"></canvas>

<script>
var draw = document.getElementById('drawing');
var time = null;
var seconds = 0;
var minutes = 0;
var hours = 0;
var secondsAngle = 0;
var minutesAngle = 0;
var hoursAngle = 0;
var secondsX = 0;
var secondsY = 0;
var minutesX = 0;
var minutesY = 0;
var hoursX = 0;
var hoursY = 0;
if (draw.getContext) {
var context = draw.getContext('2d');

// 绘制外圆
context.arc(100, 100, 99, 0, Math.PI*2, false);

// 绘制内圆
context.moveTo(194, 100);
context.arc(100, 100, 94, 0, Math.PI*2, false);
context.stroke();

context.font = "bold 14px Arial";
context.textAlign = 'center';
context.textBaseline = 'middle';
// context.fillText('12', 100, 20);
var i = 1;
var textAngle = 0;
var textX = 0;
var textY = 0;
for (i = 1; i < 13; i++) {
textAngle = i * (Math.PI*2/12);
textY = 100 - 83*Math.cos(textAngle);
textX = 100 + 83*Math.sin(textAngle);
context.fillText(i, textX, textY);
}
drawClock();
setInterval(drawClock, 1000);

}

function getTime() {
var date = new Date();
var res = {};
res.seconds = date.getSeconds();
res.minutes = date.getMinutes();
res.hours = date.getHours();
return res;
}

function drawClock() {
// 开始路径
context.beginPath();

context.clearRect(35, 35, 130, 130);



time = getTime();
seconds = time.seconds;
minutes = time.minutes;
hours = time.hours > 12 ? time.hours-12: time.hours;

// 绘制秒针
// context.rePaint();
context.moveTo(100, 100);
secondsAngle = (seconds/60)*Math.PI*2;
secondsY = 100 - 65*Math.cos(secondsAngle);
secondsX = 100 + 65*Math.sin(secondsAngle);
context.lineTo(secondsX, secondsY);


// 绘制分针
context.moveTo(100, 100);
minutesAngle = ((minutes*60+seconds)/(60*60))*Math.PI*2;
minutesY = 100 - 50*Math.cos(minutesAngle);
minutesX = 100 + 50*Math.sin(minutesAngle);
context.lineTo(minutesX, minutesY);

// 绘制时针
context.moveTo(100, 100);
hoursAngle = ((hours*60*60+minutes*60+seconds)/(12*60*60))*Math.PI*2;
hoursY = 100 - 35*Math.cos(hoursAngle);
hoursX = 100 + 35*Math.sin(hoursAngle);
context.lineTo(hoursX, hoursY);



// 描边路径
context.stroke();
}
</script>

</body>
</html>