<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>钟表效果</title>
<style>
body{background:black;}
#c1{background:white; border-radius:50%;}
</style>
</head>
<body>
<canvas id="c1" width="400" height="400">
<span>
该浏览器不支持canvas
</span>
</canvas>
<script>
var oC = document.getElementById('c1');
var oGc = oC.getContext('2d');
var x = 200;
var y = 200;
var r = 150;
clock();
setInterval(clock,1000);
function clock(){
oGc.clearRect(0,0,oC.width,oC.height);//清楚画布中的内容
var oDate = new Date();
var oHour =( -90+oDate.getHours()*30+oDate.getMinutes()/2)*Math.PI/180;
var oMin =( -90+oDate.getMinutes()*6)*Math.PI/180;
var oSec = (-90+oDate.getSeconds()*6)*Math.PI/180;//获取弧度数
oGc.beginPath();
for(var i=0; i<60; i++){//画短线
oGc.moveTo(x,y);
oGc.arc(x,y,r,6*i*Math.PI/180,6*(i+1)*Math.PI/180,false);
}
oGc.closePath();
oGc.stroke();
oGc.fillStyle = "white";//用白色填充的圆覆盖大圆的线条
oGc.beginPath();
oGc.moveTo(x,y);
oGc.arc(x,y,r*19/20,0,360,false);
oGc.closePath();
oGc.fill();
oGc.beginPath();
for(var i=0; i<12; i++){//长一点的线
oGc.moveTo(x,y);
oGc.arc(x,y,r,30*i*Math.PI/180,30*(i+1)*Math.PI/180,false);
}
oGc.closePath();
oGc.stroke();
oGc.fillStyle = "white";//用上面同样的方法覆盖
oGc.beginPath();
oGc.moveTo(x,y);
oGc.arc(x,y,r*18/20,0,360,false);
oGc.closePath();
oGc.fill();
oGc.lineWidth = 4;
oGc.beginPath();
oGc.moveTo(x,y);
oGc.arc(x,y,r*8/20,oHour,oHour,false);//时针
oGc.closePath();
oGc.stroke();
oGc.lineWidth = 2;
oGc.beginPath();
oGc.moveTo(x,y);
oGc.arc(x,y,r*12/20,oMin,oMin,false);//分针
oGc.closePath();
oGc.stroke();
oGc.save();//用save()和restore()方法,防止第二次时所有线条都变为红色的
oGc.lineWidth = 1;
oGc.strokeStyle = "red";
oGc.beginPath();
oGc.moveTo(x,y);
oGc.arc(x,y,r*14/20,oSec,oSec,false);//秒针
oGc.closePath();
oGc.stroke();
oGc.restore();
oGc.lineWidth = 1;
oGc.fillStyle = "black";
oGc.beginPath();
oGc.moveTo(x,y);
oGc.arc(x,y,r*2/50,0,360,false);
oGc.closePath();
oGc.fill();
}
</script>
</body>
</html>