<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
body {
background: #000;
}
#c1 {
background: #fff;
margin: 0 auto;
position: absolute;
left: 50%;
margin-left: -200px;
}
</style>
<script type="text/javascript">
window.onload = function() {
var oC = document.getElementById(‘c1‘);
var oGc = oC.getContext(‘2d‘);
// alert(oGc)
function toDraw() {
var x = 200;
var y = 200;
//中心点
var r = 150;
//半径
oGc.clearRect(0, 0, oC.width, oC.height)
// 获取时间
var oDate = new Date();
var oHoure = oDate.getHours();
var oMin = oDate.getMinutes();
var oSon = oDate.getSeconds();
//时针对应的弧度
var oHoureValue = (-90 + oHoure * 30 + oMin / 2) * Math.PI / 180;
//分针对应的弧度
var oMinValue = (-90 + oMin * 6) * Math.PI / 180;
//秒针对应的弧度
var oSonValue = (-90 + oSon * 6) * Math.PI / 180;
oGc.beginPath();
for(var i = 0; i < 60; i++) {
oGc.moveTo(x, y);
oGc.arc(x, y, r, 6 * i * Math.PI / 180, 6 * (i + 1) * Math.PI / 180, false)
}
oGc.closePath();
oGc.stroke();
//画白色的覆盖
oGc.fillStyle = "white";
oGc.beginPath();
oGc.moveTo(x, y);
oGc.arc(x, y, r * 19 / 20, 0, 360 * Math.PI / 180, false)
oGc.closePath();
oGc.fill();
oGc.lineWidth = 3;
oGc.beginPath();
for(var i = 0; i < 12; i++) {
oGc.moveTo(x, y);
oGc.arc(x, y, r, 30 * i * Math.PI / 180, 30 * (i + 1) * Math.PI / 180, false)
}
oGc.closePath();
oGc.stroke();
//画白色的覆盖
oGc.fillStyle = "white";
oGc.beginPath();
oGc.moveTo(x, y);
oGc.arc(x, y, r * 18 / 20, 0, 360 * Math.PI / 180, false)
oGc.closePath();
oGc.fill();
//时针
oGc.lineWidth = 5;
//分割单独的区间
oGc.beginPath();
oGc.moveTo(x, y);
oGc.arc(x, y, r * 10 / 20, oHoureValue, oHoureValue, false)
oGc.closePath();
oGc.stroke();
//分针
oGc.lineWidth = 3;
oGc.beginPath();
oGc.moveTo(x, y);
oGc.arc(x, y, r * 14 / 20, oMinValue, oMinValue, false)
oGc.closePath();
oGc.stroke();
//秒针
oGc.lineWidth = 2;
oGc.beginPath();
oGc.moveTo(x, y);
oGc.arc(x, y, r * 19 / 20, oSonValue, oSonValue, false)
oGc.closePath();
oGc.stroke();
}
setInterval(toDraw, 1000)
toDraw();
}
</script>
</head>
<body>
<canvas id="c1" width="400" height="400"></canvas>
</body>
</html>
问题:在实现 时针 分针 秒针都需要分离单独的空间 ,在开启定时器时注意要清空画布("会累加"),注意角度 ,弧度之间的转化