<view class="container">
<canvas canvas-id="clock" style="width: 300px; height: 300px;"></canvas>
</view>
Page({
onReady() {
const ctx = wx.createCanvasContext('clock');
const width = 300;
const height = 300;
const radius = width / 2;
function drawClock() {
// 清除画布
ctx.clearRect(0, 0, width, height);
// 绘制表盘
ctx.beginPath();
ctx.arc(radius, radius, radius - 10, 0, 2 * Math.PI);
ctx.setStrokeStyle('#333');
ctx.setLineWidth(10);
ctx.stroke();
ctx.closePath();
// 绘制时钟数字
ctx.setFontSize(24);
ctx.setTextAlign('center');
ctx.setTextBaseline('middle');
for (let i = 1; i <= 12; i++) {
const angle = (i * 30 * Math.PI) / 180;
const x = radius + (radius - 30) * Math.sin(angle);
const y = radius - (radius - 30) * Math.cos(angle);
ctx.fillText(i.toString(), x, y);
}
// 获取当前时间
const now = new Date();
const hours = now.getHours();
const minutes = now.getMinutes();
const seconds = now.getSeconds();
// 绘制时针
const hourAngle = ((hours % 12) * 30 + minutes / 2) * (Math.PI / 180);
drawHand(ctx, hourAngle, radius * 0.5, 8);
// 绘制分针
const minuteAngle = (minutes * 6 + seconds / 10) * (Math.PI / 180);
drawHand(ctx, minuteAngle, radius * 0.7, 5);
// 绘制秒针
const secondAngle = seconds * 6 * (Math.PI / 180);
drawHand(ctx, secondAngle, radius * 0.9, 2);
// 绘制中心圆点
ctx.beginPath();
ctx.arc(radius, radius, 5, 0, 2 * Math.PI);
ctx.setFillStyle('#333');
ctx.fill();
ctx.closePath();
// 绘制指针
ctx.draw();
}
// 绘制指针
function drawHand(ctx, angle, length, width) {
ctx.beginPath();
ctx.moveTo(radius, radius);
ctx.lineTo(
radius + length * Math.sin(angle),
radius - length * Math.cos(angle)
);
ctx.setStrokeStyle('#333');
ctx.setLineWidth(width);
ctx.stroke();
ctx.closePath();
}
// 刷新时钟
setInterval(drawClock, 1000);
drawClock(); // 初始化时钟
}
});