<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>canvas画布绘制时钟</title>
<style>
body{background: black}
#c1{background: white}
span{color:white;}
</style>
</head>
<body>
<canvas id="c1" width="400" height="400">
<span>
不支持canvas浏览器
</span>
</canvas>
<script>
var oC= document.querySelector("canvas");
var oGC=oC.getContext('2d');
//浏览器打开时停滞一秒才会运行,解决办法是封装成一个函数,开始时进行调用,在开始计时器。
//进行画布的反复绘制,从而达到时针变化的效果。
setInterval(function(){
oGC.clearRect(0,0,oC.offsetWidth,oC.offsetHeight);
//保存路径
oGC.save();
//大圆和小刻度
for(var i=0;i<60;i++)
{
oGC.beginPath();
oGC.moveTo(200,200);
oGC.arc(200,200,100,i*6*Math.PI/180,(i+1)*6*Math.PI/180,false);
oGC.stroke();
}
oGC.beginPath();
oGC.moveTo(200,200);
oGC.arc(200,200,90,0,360*Math.PI/180,false);
oGC.fillStyle="white";
oGC.fill();
//大刻度
for(var i=0;i<12;i++) {
oGC.beginPath();
oGC.moveTo(200,200);
oGC.arc(200,200,100,i*30*Math.PI/180,(i+1)*30*Math.PI/180,false);
oGC.lineWidth='2';
oGC.stroke();
}
oGC.beginPath();
oGC.fillStyle="#fff";
oGC.arc(200,200,80,0,360*Math.PI/180,false)
oGC.fill();
//时间的换算
var oD=new Date();
//canvas起点是3点位置所以-90是12点的位置。小时的转化是由小时和分钟进行转化。1小时为30度,30度为60分钟,则1分钟为0.5度
var oH=Math.floor(oD.getHours()*30-90+oD.getMinutes()/2)
//同理
var oM=Math.floor(oD.getMinutes()*6-90+oD.getSeconds()/10);
var oS=oD.getSeconds()*6-90;
//时针的绘制
oGC.beginPath();
oGC.moveTo(200,200);
oGC.arc(200,200,40,oH*Math.PI/180,oH*Math.PI/180,false);
oGC.lineWidth='4';
oGC.strokeStyle="pink";
oGC.stroke();
//分针的绘制
oGC.beginPath();
oGC.moveTo(200,200);
oGC.arc(200,200,60,oM*Math.PI/180,oM*Math.PI/180,false);
oGC.lineWidth='3';
oGC.strokeStyle="yellow";
oGC.stroke();
//秒针的绘制
oGC.beginPath();
oGC.moveTo(200,200);
oGC.arc(200,200,80,oS*Math.PI/180,oS*Math.PI/180,false);
oGC.lineWidth='2';
oGC.strokeStyle="green";
oGC.stroke();
oGC.restore();
},1000)
</script>
</body>
</html>
注意:1.圆的绘制:arc(x,y,半径,起始弧度,结束弧度,旋转方向)
3.canvas的圆的起点在3点钟的位置。
2.旋转方向:顺时针(默认:false)、逆时针(true)。
4.时间转化。