本文实例为大家分享了javascript 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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
|
<!DOCTYPE html> < html lang = "en" > < head > < meta charset = "UTF-8" > < meta name = "viewport" content = "width=device-width, initial-scale=1.0" > < title >钟表</ title > < script type = "text/javascript" > window.onload=function(){ //1.获取画布 var canvas=document.getElementById("canvas"); //2.获取上下文对象(获取画笔) var cx=canvas.getContext("2d"); //3.设置画笔样式 function clock(){ cx.fillStyle="tomato"; //4.绘制图形 //绘制表盘 cx.beginPath(); //绘制圆形 cx.arc(300,300,200,0,Math.PI*2);//设置圆 arc(x,y,r,begin,end,c);x,y:圆的圆的圆心坐标 r:圆的半径 begin,end:开始角度和结束角度;Math.PI=180 Math.PI/180=1度 c:是否按照逆时针进行绘制true:按照逆时 false:顺时针 cx.closePath();//关闭路径 cx.fill();// //绘制时刻度 cx.lineWidth=2; cx.strokeStyle="black"; for(var i=0;i< 12 ;i++){ cx.save(); cx.translate(300,300);//形移 cx.rotate(i*(Math.PI/6)); cx.beginPath(); cx.moveTo(0,-180); cx.lineTo(0,-200); cx.stroke(); cx.closePath(); cx.fillStyle = "black" ;//绘制数字 cx.font = "16px blod" ; cx.rotate(Math.PI/6); cx.fillText(i+1,-6,-220);//文字 cx.restore(); } //绘制分刻度 for(var i = 0 ;i<60;i++){ cx.save(); cx.translate(300,300); cx.rotate(i*(Math.PI/30)); cx.beginPath(); cx.moveTo(0,-190); cx.lineTo(0,-200); cx.stroke(); cx.closePath(); cx.restore(); } //获取当前时间 var today = new Date(); var hour = today .getHours(); var min = today .getMinutes(); var sec = today .getSeconds(); hour =hour+min/60; //绘制时针 cx.lineWidth = 4 ; cx.save(); cx.translate(300,300); cx.beginPath(); cx.rotate(hour*(Math.PI/6));//旋转 cx.moveTo(0,10); cx.lineTo(0,-130); cx.closePath(); cx.stroke(); cx.restore(); //回滚 //绘制分针 cx.lineWidth = 2 ; cx.save(); cx.translate(300,300); cx.beginPath(); cx.rotate(min*(Math.PI/30)); cx.moveTo(0,10); cx.lineTo(0,-160); cx.closePath(); cx.stroke(); cx.restore(); //回滚 //绘制秒针 cx.lineWidth = 1 ; cx.strokeStyle = "black" ; cx.save(); cx.translate(300,300); cx.beginPath(); cx.rotate(sec*(Math.PI/30)); cx.moveTo(0,10); cx.lineTo(0,-160); cx.closePath(); cx.stroke(); cx.restore(); //绘制交叉处 cx.fillStyle = '#ccc' ; cx.strokeStyle = "red" ; cx.save(); cx.translate(300,300); cx.beginPath(); cx.beginPath(); cx.arc(0,0,4,0,Math.PI*2); cx.closePath(); cx.fill(); cx.closePath(); cx.stroke(); cx.restore(); setTimeout(clock,1000); } // setInterval(clock,1000); clock(); } </script> </ head > < body > < canvas id = "canvas" width = "1300px" height = "600px" style = "background-color: #ccc;" ></ canvas > </ body > </ html > |
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。
原文链接:https://blog.csdn.net/weixin_46802824/article/details/108392181