可以实现时间与PC同步的时钟。
HTML框架:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>闹钟</title>
<style type="text/css">
canvas{
position:absolute;
top:10px;
left:10px;
}
</style>
</head>
<body>
<canvas id="canvas" width=“200” height="200"></canvas>
<canvas id="p_canvas" width="200" height="200"></canvas>
<script src="pp.js" type="text/javascript">
</script>
</body>
</html>
pp.js代码:
// 绘制图像
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 width=200,height=200;
//画圆
context.beginPath();
context.strokeStyle="#009999";
//context.arc(圆的中心的X坐标,圆中心的Y坐标,R的半径,起始角,结束角,false=顺时针|true=逆时针);
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);
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.lineWidth=2;
context.textAlign='center';
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.strockeStyle=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();