<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>canvas时钟</title>
<style>
body{
background: #000;
}
canvas{
background: #cccccc;
}
</style>
</head>
<body>
<canvas id="canvas" width="600" height="500"></canvas>
<script>
window.onload=function(){
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
clock();
setInterval(clock,1000);
function clock(){
var time=new Date();
var h=time.getHours();
var m=time.getMinutes();
var s=time.getSeconds();
var num=0;
ctx.beginPath();
ctx.fillStyle="#325fa2";
ctx.arc(canvas.width/2,canvas.height/2,120,0,360*Math.PI/180);
ctx.fill();
ctx.beginPath();
ctx.fillStyle="#cccccc";
ctx.arc(canvas.width/2,canvas.height/2,102,0,360*Math.PI/180);
ctx.fill();
ctx.beginPath();
ctx.strokeStyle="#000";
for(var i=0;i<60;i++){
num=6*i;
ctx.save();
ctx.beginPath();
ctx.lineCap="round";
ctx.translate(canvas.width/2,canvas.height/2);
ctx.rotate(num*Math.PI/180);
if(i%5==0){
ctx.lineWidth=5;
ctx.moveTo(84,0);
ctx.lineTo(95,0);
}else{
ctx.lineWidth=2;
ctx.moveTo(90,0);
ctx.lineTo(95,0);
}
ctx.stroke();
ctx.restore();
}
/*时针*/
ctx.save();
ctx.beginPath();
ctx.translate(canvas.width/2,canvas.height/2);
ctx.rotate((h*30+m*6/12+s*6/360)*Math.PI/180);
ctx.translate(0,10);
ctx.lineWidth=8;
ctx.moveTo(0,0);
ctx.lineTo(0,-45);
ctx.stroke();
ctx.restore();
/*分针*/
ctx.save();
ctx.beginPath();
ctx.translate(canvas.width/2,canvas.height/2);
ctx.rotate((m*6+6*s*6/360)*Math.PI/180);
ctx.translate(0,15);
ctx.lineWidth=5;
ctx.moveTo(0,0);
ctx.lineTo(0,-60);
ctx.stroke();
ctx.restore();
/*秒针*/
ctx.save();
ctx.beginPath();
ctx.strokeStyle="red";
ctx.translate(canvas.width/2,canvas.height/2);
ctx.rotate(s*6*Math.PI/180);
ctx.translate(0,16);
ctx.lineWidth=5;
ctx.moveTo(0,0);
ctx.lineTo(0,-87);
ctx.stroke();
ctx.beginPath();
ctx.arc(0,-92,5,0,360*Math.PI/180);
ctx.stroke();
ctx.restore();
ctx.beginPath();
ctx.fillStyle="red";
ctx.arc(canvas.width/2,canvas.height/2,6,0,360*Math.PI/180);
ctx.fill();
}
}
</script>
</body>
</html>