
<!doctype html>
<html>
<head>
<title>canvas</title>
</head>
<body>
<canvas id = "clock" width = "500px" height = "500px">
您的浏览器已过时,请更新!
</canvas>
<script type = "text/javascript">
var clock = document.getElementById("clock");
var cxt = clock.getContext("2d"); function drawClock(x) {
var y = x / 2;
var r = (x - 100) / 2;
var x1 = r - 10;
var x2 = r - 20;
var x3 = r - 30;
var x4 = r - 40;
var x5 = r - 50;
//清除画布
cxt.clearRect(0, 0, x, x); var now = new Date;
var sec = now.getSeconds();
var min = now.getMinutes();
var hour = now.getHours(); //解决时针的问题:1、小时之间 2、19:59:30s
hour += min / 60;
hour = hour > 12 ? hour - 12 : hour; //表盘
cxt.lineWidth = 10;
cxt.strokeStyle = "blue";
cxt.beginPath();
cxt.arc(y, y, r, 0, 360, false);
cxt.closePath();
cxt.stroke();
//时刻度
for (var i = 0; i < 12;i++ ) {
cxt.save();
cxt.lineWidth = 7;
cxt.strokeStyle = "#000";
cxt.translate(y, y);
cxt.rotate(i*30 * Math.PI / 180);
cxt.beginPath();
cxt.moveTo(0, -x1);
cxt.lineTo(0, -x3);
cxt.closePath();
cxt.stroke();
cxt.restore();
}
//分刻度
for (var i = 0; i < 60; i++) {
cxt.save();
cxt.lineWidth = 5;
cxt.strokeStyle = "#000";
cxt.translate(y, y);
cxt.rotate(i * 6 * Math.PI / 180);
cxt.beginPath();
cxt.moveTo(0, -x1);
cxt.lineTo(0, -x2);
cxt.closePath();
cxt.stroke();
cxt.restore();
}
//时针
cxt.save();
cxt.lineWidth = 7;
cxt.strokeStyle = "#000";
cxt.translate(y, y);
cxt.rotate(hour * 30 * Math.PI / 180);
cxt.beginPath();
cxt.moveTo(0, -x5);
cxt.lineTo(0, 10);
cxt.closePath();
cxt.stroke();
cxt.restore();
//分针
cxt.save();
cxt.lineWidth = 5;
cxt.strokeStyle = "#000";
cxt.translate(y, y);
cxt.rotate(min * 6 * Math.PI / 180);
cxt.beginPath();
cxt.moveTo(0, -x4);
cxt.lineTo(0, 15);
cxt.closePath();
cxt.stroke();
cxt.restore();
//秒针
cxt.save();
cxt.lineWidth = 3;
cxt.strokeStyle = "red";
cxt.translate(y, y);
cxt.rotate(sec * 6 * Math.PI / 180);
cxt.beginPath();
cxt.moveTo(0, -x3);
cxt.lineTo(0, 20);
cxt.closePath();
cxt.stroke();
cxt.lineWidth = 3;
cxt.strokeStyle = "red";
cxt.beginPath();
cxt.arc(0, 0, 5, 0, 360, false);
cxt.fillStyle = "gray";
cxt.fill();
cxt.closePath();
cxt.stroke();
cxt.lineWidth = 3;
cxt.strokeStyle = "red";
cxt.fillStyle = "red";
cxt.beginPath();
cxt.arc(0, -x5, 5, 0, 360, false);
cxt.fill();
cxt.closePath();
cxt.stroke();
cxt.restore();
} //行走
drawClock(500);
setInterval("drawClock(500)", 1000);
</script>
</body>
</html>