html5时钟实现代码
程序员文章站
2023-11-29 15:37:58
html5下实现的闹钟代码,喜欢的朋友可以参考下。
... 10-10-22...
复制代码
代码如下:<!doctype html>
<html>
<head>
<meta charset="utf-8">
<style type="text/css">
canvas{position:absolute;top:0px;left:0px;}
</style>
<title>时钟</title>
</head>
<body>
<canvas id="canvas" width="200" height="200"></canvas>
<canvas id="p_canvas" width="200" height="200"></canvas>
<script type="text/javascript">
//获取绘图对象
var canvas = document.getelementbyid('canvas');
var context = canvas.getcontext('2d');
var p_canvas = document.getelementbyid('p_canvas');
var p_context = p_canvas.getcontext('2d');
var height=200,width=200;
//画大圆
context.beginpath();
context.strokestyle="#009999";
context.arc(width/2,height/2,width/2-1,0,math.pi*2,true);
context.stroke();
context.closepath();
//画中间点
context.beginpath();
context.fillstyle="#000";
context.arc(width/2,height/2,3,0,math.pi*2,true);
context.fill();
context.closepath();
//画小刻度
var angle = 0,radius = width/2 - 4;
for(var i=0;i<60;i++){
context.beginpath();
context.strokestyle="#000";
//确认刻度的起始点
var x = width/2 + radius*math.cos(angle),y = height/2 + radius*math.sin(angle);
context.moveto(x,y);
//这里是用来将刻度的另一点指向中心点,并给予正确的角度
//pi是180度,正确的角度就是 angle+180度,正好相反方向
var temp_angle = math.pi +angle;
context.lineto(x +3*math.cos(temp_angle),y+3*math.sin(temp_angle));
context.stroke();
context.closepath();
angle+=6/180*math.pi;
}
//大刻度
angle = 0,radius = width/2 - 4;
context.textbaseline = 'middle';
context.textalign = 'center';
context.linewidth = 2;
for(var i=0;i<12;i++){
var num = i+3>12? i+3-12:i+3 ;
context.beginpath();
context.strokestyle="#ffd700";
var x = width/2 + radius*math.cos(angle),y = height/2 + radius*math.sin(angle);
context.moveto(x,y);
var temp_angle = math.pi +angle;
context.lineto(x +8*math.cos(temp_angle),y+8*math.sin(temp_angle));
context.stroke();
context.closepath();
//大刻度 文字
context.filltext(num,x+16*math.cos(temp_angle),y+16*math.sin(temp_angle));
angle+=30/180*math.pi;
}
function pointer(){
var p_type = [['#000',70,1],['#ccc',60,2],['red',50,3]];
function drwepointer(type,angle){
type = p_type[type];
angle = angle*math.pi*2 - 90/180*math.pi;
var length= type[1];
p_context.beginpath();
p_context.linewidth = type[2];
p_context.strokestyle = type[0];
p_context.moveto(width/2,height/2);
p_context.lineto(width/2 + length*math.cos(angle),height/2 + length*math.sin(angle));
p_context.stroke();
p_context.closepath();
}
setinterval(function (){
p_context.clearrect(0,0,height,width);
var time = new date();
var h = time.gethours();
var m = time.getminutes();
var s = time.getseconds();
h = h>12?h-12:h;
h = h+m/60;
h=h/12;
m=m/60;
s=s/60;
drwepointer(0,s);
drwepointer(1,m);
drwepointer(2,h);
},500);
}
var p = new pointer();
</script>
</body>
</html>