效果如下
代码如下
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<style type="text/css">
canvas{
border:1px solid #000;
}
</style>
</head>
<body>
<canvas id="canvas" width="600" height="600"></canvas>
</body>
<script type="text/javascript">
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext('2d');
// //外部表盘
// function wbp(){
// ctx.beginPath(); //画笔开始
// ctx.lineWidth = 5; //设置画笔的线宽
// ctx.strokeStyle="blue"; //设置画笔的颜色
// ctx.arc(250,250,200,0,360,false); //绘制圆形,坐标250,250 半径200,整圆(0-360度),false表示顺时针
// ctx.stroke(); //绘图
// ctx.closePath(); //结束画布
// }
function hbp(){
//时针刻度
var num = 0;
for(var i=0; i<12; i++){
//设置旋转环境
ctx.save();
//设置时针的样式
ctx.lineWidth=7;
ctx.strokeStyle="#000";
num+=30;
ctx.translate(250,250);//设置异次元空间的原点
ctx.rotate(num*Math.PI/180);//设置旋转角度
ctx.beginPath(); //画笔开始
ctx.moveTo(0,-170); //画线, 从坐标0,-170开始
ctx.lineTo(0,-190); //到坐标0,-190结束
ctx.stroke(); //绘图
ctx.closePath();
//将旋转之后的元素放回原画布
ctx.restore();
}
}
//分针刻度
function fbp(){
var f=0
for(var i = 0;i<60;i++){
ctx.save();
ctx.lineWidth = '5';
ctx.strokeStyle = '#000';
f+=6
ctx.translate(250,250);
ctx.rotate(f*Math.PI/180);
ctx.beginPath();
ctx.moveTo(0,-180);
ctx.lineTo(0,-190);
ctx.stroke();
ctx.closePath();
ctx.restore();
}
}
//时针
function sz(hou){
ctx.save();
ctx.lineWidth = '7';
ctx.strokeStyle = '#000';
ctx.translate(250,250);
ctx.rotate(30*hou*Math.PI/180);
ctx.beginPath();
ctx.moveTo(0,-110);
ctx.lineTo(0,10);
ctx.stroke();
ctx.closePath();
ctx.restore();
}
//分针
function fz(mi){
ctx.save();
ctx.lineWidth = '5';
ctx.strokeStyle = '#000';
ctx.translate(250,250);
ctx.rotate(6*mi*Math.PI/180);
ctx.beginPath();
ctx.moveTo(0,-140);
ctx.lineTo(0,10);
ctx.stroke();
ctx.closePath();
ctx.restore();
}
//秒针
function mz(se,see){
ctx.save();
ctx.lineWidth = '3';
ctx.strokeStyle = '#000';
ctx.translate(250,250);
let s = 0.006 * ((new Date).getSeconds() * 1000 + (new Date).getMilliseconds() + 30000) * Math.PI / 180; //超好看效果
// ctx.rotate(6*se*Math.PI/180);
ctx.rotate(s);
ctx.beginPath();
ctx.moveTo(0,-140);
ctx.lineTo(0,10);
ctx.stroke();
ctx.closePath();
ctx.restore();
}
var timer = setInterval(function(){
//获取本地时间
var date = new Date();
var hou = date.getHours();
var mi = date.getMinutes();
var se = date.getSeconds();
var see = date.getMilliseconds();
ctx.clearRect(0,0,600,600);
sz(hou);
fz(mi);
mz(se,see);
// wbp();
hbp();
fbp()
},1)
</script>
</html>