您的位置:首页 > Web前端 > HTML5

HTML5元素Canvas实例之钟表

2012-11-23 10:48 399 查看


[代码] HTML5代码

view
source

print?

001
<!DOCTYPE
 html>
002
<
html
>
003
<
head
>
004
<
script
type
=
"text/javascript"
>
005
function
 init(){
006
clock();
007
setInterval(clock,1000);
008
}
009
function
 clock(){
010
var
 now =new Date();
011
var
 ctx =document.getElementById('canvas').getContext('2d');
012
ctx.save();
013
ctx.clearRect(0,0,150,150);
014
ctx.translate(75,75);
015
ctx.scale(0.4,0.4);
016
ctx.rotate(-Math.PI/2);
017
ctx.strokeStyle
 ="black";
018
ctx.fillStyle
 ="white";
019
ctx.lineWidth
 =8;
020
ctx.lineCap
 ="round";
021
 
022
//
 Hour marks
023
ctx.save();
024
for
 (vari=0;i<
12
;i++){
025
ctx.beginPath();
026
ctx.rotate(Math.PI/6);
027
ctx.moveTo(100,0);
028
ctx.lineTo(120,0);
029
ctx.stroke();
030
}
031
ctx.restore();
032
 
033
//
 Minute marks
034
ctx.save();
035
ctx.lineWidth
=
5
;
036
for
 (
i
=
0
;i<60;i++){
037
if
 (i%5!=0) {
038
ctx.beginPath();
039
ctx.moveTo(117,0);
040
ctx.lineTo(120,0);
041
ctx.stroke();
042
}
043
ctx.rotate(Math.PI/30);
044
}
045
ctx.restore();
046
 
047
var
sec
=
now
.getSeconds();
048
var
min
=
now
.getMinutes();
049
var
hr
=
now
.getHours();
050
hr
=
hr>=12 ? hr-12 : hr;
051
 
052
ctx.fillStyle
="black";
053
 
054
//
 write Hours
055
ctx.save();
056
ctx.rotate(
hr*(Math.PI/6) +(Math.PI/360)*min +(Math.PI/21600)*sec )
057
ctx.lineWidth
=14;
058
ctx.beginPath();
059
ctx.moveTo(-20,0);
060
ctx.lineTo(80,0);
061
ctx.stroke();
062
ctx.restore();
063
 
064
//
 write Minutes
065
ctx.save();
066
ctx.rotate(
(Math.PI/30)*min +(Math.PI/1800)*sec )
067
ctx.lineWidth
=10;
068
ctx.beginPath();
069
ctx.moveTo(-28,0);
070
ctx.lineTo(112,0);
071
ctx.stroke();
072
ctx.restore();
073
 
074
//
 Write seconds
075
ctx.save();
076
ctx.rotate(sec
* Math.PI/30);
077
ctx.strokeStyle
="#D40000";
078
ctx.fillStyle
="#D40000";
079
ctx.lineWidth
=6;
080
ctx.beginPath();
081
ctx.moveTo(-30,0);
082
ctx.lineTo(83,0);
083
ctx.stroke();
084
ctx.beginPath();
085
ctx.arc(0,0,10,0,Math.PI*2,true);
086
ctx.fill();
087
ctx.beginPath();
088
ctx.arc(95,0,10,0,Math.PI*2,true);
089
ctx.stroke();
090
ctx.fillStyle
="#555";
091
ctx.arc(0,0,3,0,Math.PI*2,true);
092
ctx.fill();
093
ctx.restore();
094
 
095
ctx.beginPath();
096
ctx.lineWidth
=14;
097
ctx.strokeStyle
='#325FA2';
098
ctx.arc(0,0,142,0,Math.PI*2,true);
099
ctx.stroke();
100
 
101
ctx.restore();
102
}
103
104
</
script
>
105
 
106
</
head
>
107
<
body
onload
=
"init();"
>
108
<
canvas
id
=
"canvas"
width
=
"150"
height
=
"150"
></
canvas
>
109
</
body
>
110
</
html
>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: