如题:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div style="border:1px solid red;width:500px;height:500px;margin:0 auto">
<!--html5新标记: 简单理解为画布 -->
<canvas id="can" width="500" height="500" style="background:#ccc">
您的浏览器不支持html5,请更换!
</canvas>
</div>
<script>
//1 找到画布
var clock = document.getElementById("can");
//2 获取画笔
var hb = clock.getContext("2d");
// 5 将绘制的代码封装为一个整体
function getTime(){
//7 清除之前画布上的图片
hb.clearRect(0,0,500,500);
//3 绘制表
// 3.1 绘制表盘
hb.beginPath(); //开启路径
hb.strokeStyle="#DAA520"; //画笔的颜色
hb.lineWidth=10; //画笔的宽度
hb.arc(250,250,200,0,2*Math.PI,false); // 绘制一个圆(x,y,r,起始弧度,最终弧度,顺时针)
hb.stroke(); //执行
hb.closePath(); //关闭路径
// 3.2 绘制时针
for(var i = 0; i < 12; i++){
hb.save(); //开启异次元,可以重新设置中心点
hb.translate(250,250); //设置新零点
hb.rotate(i*30*Math.PI/180); //旋转弧度()
hb.beginPath();
hb.strokeStyle="#DAA520"; //画笔颜色
hb.lineWidth=5; //画笔的宽度
hb.moveTo(0,-195);
hb.lineTo(0,-175);
hb.stroke(); //执行
// 添加数字
hb.fillStyle = '#000'; //文字颜色填充
hb.font = '20px 微软雅黑';
if(i==0){
hb.fillText(12+'',-6,-150);
}
else{
hb.fillText(i+'',-6,-150);
}
hb.closePath();
hb.restore(); //闭合异次元
}
// 3.3 绘制分刻度(60根,每次偏转6度。长度10,宽度5)
for(var i = 0; i < 60; i++){
hb.save();
hb.translate(250,250);
hb.rotate(i*30*Math.PI/180/5);
hb.beginPath();
hb.strokeStyle="#DAA520";
hb.lineWidth=1;
hb.moveTo(0,-195);
hb.lineTo(0,-185);
hb.stroke();
hb.closePath();
hb.restore();
}
// 4 获取当前时间,计算各指针旋转角度
var now = new Date();//当前时间
var hours = now.getHours();//获取小时数
var min = now.getMinutes();//获取分针数
var secs = now.getSeconds();//获取秒数
hours = hours + min/60;
// 3.4 绘制时针
hb.save();
hb.translate(250,250);
hb.rotate(30*hours*Math.PI/180);
hb.beginPath();
hb.strokeStyle="#000";
hb.lineWidth=7;
hb.moveTo(0,10);
hb.lineTo(0,-80);
hb.stroke();
hb.closePath();
hb.restore();
// 3.5 绘制分针
hb.save();
hb.translate(250,250);
hb.rotate(6*min*Math.PI/180);
hb.beginPath();
hb.strokeStyle="#000";
hb.lineWidth=5;
hb.moveTo(0,10);
hb.lineTo(0,-100);
hb.stroke();
hb.closePath();
hb.restore();
// 3.6 绘制秒针
hb.save();
hb.translate(250,250);
hb.rotate(secs*6*Math.PI/180);
hb.beginPath();
hb.strokeStyle="#000";
hb.lineWidth=3;
hb.moveTo(0,10);
hb.lineTo(0,-120);
hb.stroke();
hb.closePath();
// 画中心红圆
hb.beginPath();
hb.strokeStyle="#f00";
hb.lineWidth=2;
hb.arc(0,0,4,0,2*Math.PI,false);
hb.stroke();
hb.closePath();
//填充
hb.fillStyle="#f00";
hb.fill();
hb.restore();
}
// 6 定时执行封装的代码
// 每个1000毫秒(1秒)执行一个getTime
setInterval(getTime,1000);
// 8 消除刷新延迟
getTime();
</script>
</body>
</html>