<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>canvas</title>
<style>
canvas{
display: block;
border:2px solid blue;
margin:0 auto;
}
</style>
</head>
<body>
<canvas width="500" height="500" id="canvas"></canvas>
<script>
var canvas=document.getElementById('canvas');
var cxt=canvas.getContext('2d');
function gettime(){
//清空画布
cxt.clearRect(0,0,500,500);
//设置线宽颜色
cxt.strokeStyle='red';
cxt.lineWidth=2;
//时钟圆心
cxt.beginPath();
cxt.fillStyle='blue';
cxt.arc(250,250,5,0,Math.PI*2);
cxt.closePath();
cxt.fill();
cxt.stroke();
//绘制圆形
cxt.beginPath();
cxt.arc(250,250,250,0,Math.PI*2);
cxt.closePath();
cxt.stroke();
//获取当前时间并显示
var nowtime=new Date;
var h=nowtime.getHours(),
m=nowtime.getMinutes(),
s=nowtime.getSeconds();
cxt.font='25px 微软雅黑';
cxt.textAlign='center';
cxt.fillStyle='red';
cxt.fillText(totwo(h)+':'+totwo(m)+':'+totwo(s),250,450);
h=h>12?h-12:h;//十二小时制
//十二小时指针旋转角度
var rotateH=h*Math.PI/6;//时针
var rotateM=m*Math.PI/30;//分针
var rotateS=s*Math.PI/30;//秒针
for(var i=1;i<=12;i++){
//显示时刻表
cxt.save();//存储信息
cxt.translate(250,250);
cxt.fillStyle='black';
cxt.font='20px 微软雅黑';
cxt.textAlign='center';
cxt.textBaseline='middle';
var x=230*Math.sin(Math.PI*i/6);
var y=230*Math.cos(Math.PI*i/6);
cxt.fillText(i,x,-y);
cxt.restore();//释放信息
}
//绘制时针
dravpointer({
rotate:rotateH,
width:5,
color:'green',
length:100
});
//绘制分针
dravpointer({
rotate:rotateM,
width:4,
color:'black',
length:150
});
//绘制秒针
dravpointer({
rotate:rotateS,
width:3,
color:'blue',
length:200
});
}
function totwo(num){
//用于补位,当时间数字小于10,用0占位显示01,02,03...
return num<10?'0'+num:num;
}
function dravpointer(pointers){
/*用于绘画指针,opinters是个对象
{
rotate:旋转角度,
width:线宽,
color:颜色,
length:长度
}
* */
cxt.save();
cxt.translate(250,250);
cxt.rotate(pointers.rotate);
cxt.beginPath();
cxt.strokeStyle=pointers.color;
cxt.lineWidth=pointers.width;
cxt.moveTo(0,0);
cxt.lineTo(0,-pointers.length);
cxt.closePath();
cxt.stroke();
cxt.restore();
}
gettime();
//持续绘制时钟,让时钟动起来
setInterval(gettime,1000);
</script>
</body>
</html>