实现HTML5 Canvas绘制时钟
时间: 2024-02-25 16:57:14 浏览: 102
好的,下面是一个简单的HTML5 Canvas绘制时钟的示例代码:
```
<!DOCTYPE html>
<html>
<head>
<title>Canvas时钟</title>
<style>
canvas {
border: 2px solid black;
}
</style>
</head>
<body>
<canvas id="clock" width="200" height="200"></canvas>
<script>
function drawClock() {
// 获取Canvas元素
var canvas = document.getElementById("clock");
var ctx = canvas.getContext("2d");
// 获取Canvas中心点坐标
var centerX = canvas.width / 2;
var centerY = canvas.height / 2;
// 绘制表盘
ctx.beginPath();
ctx.arc(centerX, centerY, 80, 0, 2 * Math.PI);
ctx.strokeStyle = "black";
ctx.stroke();
// 绘制刻度
for (var i = 1; i <= 12; i++) {
var angle = i * Math.PI / 6;
var x = centerX + 60 * Math.sin(angle);
var y = centerY - 60 * Math.cos(angle);
ctx.beginPath();
ctx.arc(x, y, 5, 0, 2 * Math.PI);
ctx.fillStyle = "black";
ctx.fill();
}
// 绘制时针
var now = new Date();
var hour = now.getHours() % 12;
var minute = now.getMinutes();
var second = now.getSeconds();
var hourAngle = (hour + minute / 60) * Math.PI / 6;
var hourX = centerX + 40 * Math.sin(hourAngle);
var hourY = centerY - 40 * Math.cos(hourAngle);
ctx.beginPath();
ctx.moveTo(centerX, centerY);
ctx.lineTo(hourX, hourY);
ctx.strokeStyle = "black";
ctx.stroke();
// 绘制分针
var minuteAngle = minute * Math.PI / 30;
var minuteX = centerX + 60 * Math.sin(minuteAngle);
var minuteY = centerY - 60 * Math.cos(minuteAngle);
ctx.beginPath();
ctx.moveTo(centerX, centerY);
ctx.lineTo(minuteX, minuteY);
ctx.strokeStyle = "black";
ctx.stroke();
// 绘制秒针
var secondAngle = second * Math.PI / 30;
var secondX = centerX + 60 * Math.sin(secondAngle);
var secondY = centerY - 60 * Math.cos(secondAngle);
ctx.beginPath();
ctx.moveTo(centerX, centerY);
ctx.lineTo(secondX, secondY);
ctx.strokeStyle = "red";
ctx.stroke();
}
// 每秒钟更新时钟
setInterval(drawClock, 1000);
</script>
</body>
</html>
```
这段代码使用Canvas绘制了一个时钟,并且每秒钟更新一次。你可以将代码复制到一个HTML文件中运行,就可以看到时钟的效果了。
阅读全文