style样式
<style>
canvas{
border: 1px solid red;
}
</style>
html样式
<body>
<canvas id="can" width="500" height="500"></canvas>
</body>
script样式
<script>
var can = document.getElementById('can');
var cx = can.getContext('2d');
var r = can.width/2;
// 重置原点
cx.translate(r,r);
setInterval(function () {
// 清空前面所画的东西 (基点x,基点y,宽,高)
cx.clearRect(-r,-r,2*r,2*r);
// 画圆圈
cx.beginPath();
cx.arc(0,0,r-2,0,2*Math.PI); // (原点x,原点y,半径,0度,2π度)
cx.lineWidth = 3; // 线条的宽度
cx.stroke();
for (var i=0; i<60; i++){
cx.rotate(Math.PI/30); // 旋转的角度 2π/60
// 画刻度
cx.beginPath();
cx.moveTo(r-20,0);
cx.lineTo(r-2,0);
cx.stroke();
}
for (var i=0; i<12; i++){
cx.rotate(Math.PI/6);
// 画12个刻度
cx.beginPath();
cx.lineWidth = 5;
cx.moveTo(r-30,0);
cx.lineTo(r-2,0);
cx.stroke();
}
//画数字
for (var i=1; i<=12; i++){
cx.beginPath();
cx.font = '24px 微软雅黑';
cx.textBaseline = 'middle'; // 垂直居中
cx.textAlign = 'center'; // 水平居中
cx.fillText(i,(r-45)*Math.sin(Math.PI/6 * i),-(r-45)*Math.cos(Math.PI/6 * i)); // (数值,x,y)
cx.stroke();
}
// 获取时间
var date = new Date();
var hour = date.getHours();
var min = date.getMinutes();
var sec = date.getSeconds();
// 画时针
cx.save(); // 与后面的restore配对,防止里面的设置影响到外面
cx.beginPath();
cx.rotate(Math.PI/6 * (hour + min/60 + sec/3600));
cx.moveTo(0,40);
cx.lineTo(0,-100);
cx.lineWidth = 8;
cx.stroke();
cx.restore();
// 画分针
cx.save();
cx.beginPath();
cx.rotate(Math.PI/30 * (min + sec/60));
cx.moveTo(0,50);
cx.lineTo(0,-150);
cx.lineWidth = 4;
cx.stroke();
cx.restore();
// 画秒针
cx.save();
cx.beginPath();
cx.rotate(Math.PI/30 * (sec));
cx.moveTo(0,60);
cx.lineTo(0,-200);
cx.lineWidth = 2;
cx.strokeStyle = 'red';
cx.stroke();
cx.restore();
// 画表盘中心点
cx.beginPath();
cx.arc(0,0,10,0,2*Math.PI);
cx.fill();
},1000)
</script>