<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>rotate</title>
</head>
<body>
<canvas id='canvas' width="300" height="300"></canvas>
<script>
function rotateFun(){
var now= new Date();//获取当前时间对象,对以后指针旋转很重要
var ctx=document.getElementById("canvas").getContext("2d");//取的画布环境
ctx.clearRect(0,0,800,600);//在开始之前都要清空画布,因为不清空就会所有的痕迹在画布上显示
ctx.save();//第一个保存状态
ctx.fillStyle='rgba(20,20,20,0.2)';
ctx.fillRect(0,0,800,600);
ctx.translate(150,150);//平移画布中心到中心
//画12个小时
ctx.save();
for (var i = 0; i < 12; i++) {
ctx.strokeStyle='black';
ctx.rotate(2*Math.PI/12);
ctx.moveTo(120,0);
ctx.lineTo(100,0);
ctx.lineWidth=8;
ctx.stroke();
}
ctx.restore();
//画60个分钟
ctx.save();
for (var i = 0; i <60 ;i++) {
ctx.strokeStyle='black';
ctx.rotate(2*Math.PI/60);
ctx.moveTo(115,0);
ctx.lineTo(105,0);
ctx.lineWidth=2;
ctx.stroke();
}
ctx.restore();
var hour=now.getHours();
var min=now.getMinutes();
var sec=now.getSeconds();
//画秒针
ctx.save();
ctx.beginPath();
ctx.rotate(sec*Math.PI/30);
ctx.strokeStyle='black';
ctx.lineWidth=4;
ctx.moveTo(0,30);
ctx.lineTo(0,-112);
ctx.stroke();
ctx.closePath();
ctx.restore();
//画分钟
ctx.save();
ctx.beginPath();
ctx.rotate(min*Math.PI/30+sec*Math.PI/1800);
ctx.strokeStyle='black';
ctx.lineWidth=6;
ctx.moveTo(0,28);
ctx.lineTo(0,-83);
ctx.stroke();
ctx.closePath();
ctx.restore();
//画时钟
ctx.save();
ctx.beginPath();
ctx.rotate(hour*Math.PI/6+min*Math.PI/360+sec*Math.PI/21600);
ctx.strokeStyle='black';
ctx.lineWidth=8;
ctx.moveTo(0,26);
ctx.lineTo(0,-63);
ctx.stroke();
ctx.closePath();
ctx.beginPath();
ctx.strokeStyle='blue';
ctx.arc(0,0,126,0,2*Math.PI);
ctx.stroke();
ctx.closePath();
ctx.restore();
ctx.restore();
window.requestAnimationFrame(rotateFun);
}
rotateFun();
</script>
</body>
</html>
浏览后显示的效果为: