下面是时钟绘制代码:
使用canvas绘制时钟
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
var clock = document.getElementById('clock');
//建立绘图环境
var cxt = clock.getContext('2d');
//时钟绘制函数
function drawClock(x, y, radius){
cxt.clearRect(0, 0, x*2, y*2);
//画表盘
cxt.beginPath();
cxt.strokeStyle = "#40bca3";
cxt.lineWidth = 10;
cxt.arc(x, y, radius, 0, 360, false);
cxt.stroke();
cxt.closePath();
//画刻度
for(var i=0; i<12; i++){
cxt.save();
cxt.translate(x, y);//设置原点
cxt.strokeStyle = "#e84849";//颜色
cxt.lineWidth = 7;//粗细
//弧度
cxt.rotate(i*30*Math.PI/180);
cxt.beginPath();
cxt.moveTo(0, radius - 20);
cxt.lineTo(0, radius - 10);
cxt.stroke();
cxt.closePath();
cxt.restore();
}
//获取当前时间
var date = new Date();
var hour = date.getHours();
var min = date.getMinutes();
var sec = date.getSeconds();
hour = hour + min/60;
hour?hour>12:hour-12;
//画时针
cxt.save();
cxt.strokeStyle = "#000";
cxt.lineWidth = 8;
cxt.translate(x, y);
cxt.rotate(hour*30*Math.PI/180);
cxt.beginPath();
cxt.moveTo(0,-radius+60);
cxt.lineTo(0,10);
cxt.stroke();
cxt.closePath();
cxt.restore();
//画分针
cxt.save();
cxt.strokeStyle = "#000";
cxt.lineWidth = 5;
cxt.translate(x, y);
cxt.rotate(min*6*Math.PI/180);
cxt.beginPath();
cxt.moveTo(0,-radius+40);
cxt.lineTo(0,10);
cxt.stroke();
cxt.closePath();
cxt.restore();
//画秒针
cxt.save();
cxt.strokeStyle="#e84849";
cxt.lineWidth = 2;
cxt.translate(x, y);
cxt.rotate(6*sec*Math.PI/180);
cxt.beginPath();
cxt.moveTo(0,-radius+30);
cxt.lineTo(0,15);
cxt.closePath();
cxt.stroke();
//画表中间的圆点
cxt.beginPath();
cxt.arc(0,0,5,0,360,false);
cxt.closePath();
cxt.fillStyle = "#fff";
cxt.fill();
cxt.stroke();
cxt.closePath();
cxt.restore();
}
setInterval("drawClock(120, 120, 100)",1000);