基于Canvas的时钟

效果比较简单,没有放满各个时刻(网上这类例子很多)

image

这里有一点取巧:画完外圈圆、内圈圆后,将原点(默认为0,0)转换为圆的中心点,这样的话,只需要知道角度,在已知时针、分针、秒针它的长度情况下,很容易求出对应的坐标(x, y)

image

在求的时候需要注意的是,先要将得到的弧度 – 1/2*Math.PI,以时针为例,一圈分为12个刻度,那么1个小时对应的弧度为 hour * 30 * Math.PI / 180 – 1/2*Math.PI。

完整的示例代码:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<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>

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

function drawClock() {
var radius = 100;
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>

在线运行示例:

原文地址:https://www.cnblogs.com/meteoric_cry/p/2117801.html