由canvas中的beginPath(),stroke()来绘制钟表的指针和点数
在然后用一个函数封装,用间歇调用setInterval(handler,1000)来让函数每一秒绘制一个表,到达动态的效果
代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>用canvas绘制钟表</title>
<style>
#cv{
border: 1px solid #333;
}
</style>
<script>
window.onload=function(){
var cv=document.getElementById("cv");
var ctx=cv.getContext("2d");
setInterval(toDrawClock,1000)
function toDrawClock(){
var x=200;
var y=200;
var r=150;
ctx.clearRect(0,0,cv.width,cv.height);
// 获取本地时间
var oDate=new Date();
var oHours=oDate.getHours();
var oMinutes=oDate.getMinutes();
var oSeconds=oDate.getSeconds();
// 计算当前时间对应的弧度
var oHoursValue=(-90+oHours*30+oMinutes/2)*Math.PI/180;
var oMinutesValue=(-90+oMinutes*6+oSeconds/10)*Math.PI/180;
var oSecondsValue=(-90+oSeconds*6)*Math.PI/180;
// 分针刻度,每6度一分钟
ctx.beginPath();
for(var i=0;i<60;i++){
ctx.moveTo(x, y);
ctx.arc(x, y, r, 6*i* Math.PI / 180, 6*(i+1) * Math.PI / 180);
}
ctx.closePath();
ctx.stroke();
ctx.fillStyle = "white";
ctx.beginPath();
ctx.moveTo(x, y);
ctx.arc(x, y, 19/20*r,0, 360 * Math.PI / 180);
ctx.closePath();
ctx.fill();
// 时针刻度,每30度一小时
ctx.beginPath();
ctx.lineWidth=3;
for(var i=0;i<12;i++){
ctx.moveTo(x, y);
ctx.arc(x, y, r, 30*i* Math.PI / 180, 30*(i+1) * Math.PI / 180);
}
ctx.closePath();
ctx.stroke();
ctx.fillStyle = "white";
ctx.beginPath();
ctx.moveTo(x, y);
ctx.arc(x, y, 18/20*r,0, 360 * Math.PI / 180);
ctx.closePath();
ctx.fill();
// 绘制时针
ctx.beginPath();
ctx.lineWidth=6;
ctx.moveTo(x, y);
ctx.arc(x, y, 12/20*r,oHoursValue,oHoursValue);
ctx.closePath();
ctx.stroke();
// 绘制分针
ctx.beginPath();
ctx.lineWidth=4;
ctx.moveTo(x, y);
ctx.arc(x, y, 16/20*r,oMinutesValue, oMinutesValue);
ctx.closePath();
ctx.stroke();
// 绘制秒针
ctx.beginPath();
ctx.lineWidth=2;
ctx.moveTo(x, y);
ctx.arc(x, y, 18/20*r,oSecondsValue, oSecondsValue);
ctx.closePath();
ctx.stroke();
// ctx.font = '5px 宋体';
// ctx.fillText('12',200,80)
}
}
</script>
</head>
<body>
<div style="text-align: center;">
<canvas id="cv" width="400px" height="400px">
不支持的浏览器
</canvas>
</div>
</body>
</html>