要在h5 canvas中绘画钟表,需要使用JavaScript来处理绘图逻辑。以下是一个简单的示例代码:
HTML代码:
<!DOCTYPE html>
<html>
<head>
<title>Canvas Clock</title>
<style>
canvas {
border: 1px solid black;
}
</style>
</head>
<body>
<canvas id="clockCanvas" width="200" height="200"></canvas>
<script src="script.js"></script>
</body>
</html>
JavaScript代码(script.js):
window.onload = function () {
// 获取canvas元素
var canvas = document.getElementById("clockCanvas");
var ctx = canvas.getContext("2d");
// 设置钟表的半径
var radius = canvas.height / 2;
// 将原点设置为钟表的中心点
ctx.translate(radius, radius);
// 缩放canvas元素,使得钟表显示在合适的大小
radius *= 0.9;
ctx.scale(radius, radius);
// 绘制钟表
drawClock();
// 创建绘制钟表的函数
function drawClock() {
drawFace(ctx, radius);
drawNumbers(ctx, radius);
drawTime(ctx, radius);
}
// 绘制钟表的外圈
function drawFace(ctx, radius) {
ctx.beginPath();
ctx.arc(0, 0, radius, 0, 2 * Math.PI);
ctx.fillStyle = "white";
ctx.fill();
ctx.lineWidth = 2;
ctx.stroke();
ctx.closePath();
}
// 绘制钟表上的数字
function drawNumbers(ctx, radius) {
var ang;
var num;
ctx.font = radius * 0.15 + "px arial";
ctx.textBaseline = "middle";
ctx.textAlign = "center";
for (num = 1; num <= 12; num++) {
ang = num * Math.PI / 6;
ctx.rotate(ang);
ctx.translate(0, -radius * 0.85);
ctx.rotate(-ang);
ctx.fillText(num.toString(), 0, 0);
ctx.rotate(ang);
ctx.translate(0, radius * 0.85);
ctx.rotate(-ang);
}
}
// 绘制当前时间的时、分、秒针
function drawTime(ctx, radius) {
var now = new Date();
var hour = now.getHours();
var minute = now.getMinutes();
var second = now.getSeconds();
// 绘制时针
hour = hour % 12;
hour = (hour * Math.PI / 6) + (minute * Math.PI / (6 * 60)) + (second * Math.PI / (360 * 60));
drawHand(ctx, hour, radius * 0.5, radius * 0.07);
// 绘制分针
minute = (minute * Math.PI / 30) + (second * Math.PI / (30 * 60));
drawHand(ctx, minute, radius * 0.8, radius * 0.07);
// 绘制秒针
second = (second * Math.PI / 30);
drawHand(ctx, second, radius * 0.9, radius * 0.02);
}
// 绘制时、分、秒针
function drawHand(ctx, pos, length, width) {
ctx.beginPath();
ctx.lineWidth = width;
ctx.lineCap = "round";
ctx.moveTo(0, 0);
ctx.rotate(pos);
ctx.lineTo(0, -length);
ctx.stroke();
ctx.rotate(-pos);
}
// 每秒钟更新一次钟表
setInterval(drawClock, 1000);
};
这段代码使用 h5 canvas 绘制了一个简单的钟表。在drawClock
函数中,我们先绘制了钟表的外圈,然后绘制了钟表上的数字,最后根据当前的时间绘制了时、分、秒针。drawHand
函数用于绘制时、分、秒针。
在window.onload
事件中,我们获取了clockCanvas
元素,并获取了它的2D绘图上下文。通过设置画布的原点和缩放比例,我们将钟表绘制在合适的位置和大小。
最后,我们使用setInterval
方法每秒钟更新一次钟表。