# 基于Canvas的时钟

```<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Canvas Clock</title>
<style type="text/css">
body {background-color:#fff; font-size:12px; font-family:arial, sans-serif;}
</style>
<body>

<canvas id="clock" width="300" height="300">
您当前使用的浏览器不支持Canvas
</canvas>

<script type="text/javascript">
var clock = document.getElementById("clock");
var ctx = null;

function drawClock() {
var hourWidth = 60;
var minutesWidth = 80;
var secondsWidth = 90;

var date = new Date();
var hour = date.getHours();
var minutes = date.getMinutes();
var seconds = date.getSeconds();

if (hour > 12) {
hour -= 12;
}

var hourAngle = (hour * 30 - 90) * Math.PI / 180;
var minutesAngle = (minutes * 6 - 90) * Math.PI / 180;
var secondsAngle = (seconds * 6 - 90) * Math.PI / 180;

//console.log(hour + ":" + minutes + ":" + seconds);

ctx = clock.getContext("2d");
ctx.save();
ctx.translate(0, 0);
ctx.clearRect(0, 0, clock.width, clock.height);
ctx.strokeStyle = "black";

ctx.save();

//绘制路径
ctx.beginPath();

//绘制外圈
ctx.arc(200, 200, 99, 0, 2*Math.PI, false);

//绘制内圈
ctx.moveTo(295, 200);
ctx.arc(200, 200, 95, 0, 2*Math.PI, false);

//路径描边
ctx.stroke();

ctx.restore();

ctx.save();
ctx.translate(200, 200);
ctx.font = "bold 10px Arial";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillText("12", 0, -88);
ctx.fillText("3", 88, 0);
ctx.fillText("6", 0, 88);
ctx.fillText("9", -88, 0);
ctx.stroke();
ctx.restore();

//绘制时针        长度为80px
ctx.save();
ctx.beginPath();
ctx.translate(200, 200);
ctx.strokeStyle = "green";
ctx.moveTo(0, 0);
ctx.lineTo(hourWidth * Math.cos(hourAngle), hourWidth * Math.sin(hourAngle));
ctx.stroke();
ctx.restore();

//绘制分针          长度为60px
ctx.save();
ctx.beginPath();
ctx.translate(200, 200);
ctx.strokeStyle = "blue";
ctx.moveTo(0, 0);
ctx.lineTo(minutesWidth * Math.cos(minutesAngle), minutesWidth * Math.sin(minutesAngle));
ctx.stroke();
ctx.restore();

//绘制秒针          长度为90
ctx.save();
ctx.translate(200, 200);
ctx.strokeStyle = "red";
ctx.beginPath();
ctx.moveTo(0, 0);
ctx.lineTo(secondsWidth * Math.cos(secondsAngle), secondsWidth * Math.sin(secondsAngle));
ctx.stroke();
ctx.restore();
}

if (clock.getContext) {
drawClock();

setInterval(drawClock, 1000);
}

</script>

</body>
</html>```

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <title>Canvas Clock</title> <style type="text/css"> * {margin:0; padding:0;} body {background-color:#fff; font-size:12px; font-family:arial, sans-serif;} </style> </head> <body> <canvas id="clock" width="300" height="300"> 您当前使用的浏览器不支持Canvas </canvas> </body> </html> 预览代码

413 篇文章24 人订阅

0 条评论