<template>
<view class="container">
<view class="time">
<canvas canvas-id="clockCanvas" class="clock"></canvas>
</view>
</view>
</template>
<script>
export default {
data() {
return {
clockTimer: null, // 时钟定时器
clockContext: null, // 时钟绘图上下文
};
},
onReady() {
this.clockContext = uni.createCanvasContext('clockCanvas');
this.startClock();
},
methods: {
startClock() {
this.clockTimer = setInterval(() => {
this.drawClock();
}, 1000);
},
stopClock() {
if (this.clockTimer) {
clearInterval(this.clockTimer);
this.clockTimer = null;
}
},
drawClock() {
const ctx = this.clockContext;
// 清空画布
ctx.clearRect(0, 0, 300, 300);
// 绘制表盘
ctx.beginPath();
ctx.arc(45, 45, 42, 0, 2 * Math.PI); //第一、二个参数为表盘位置,第三个参数为表盘大小
ctx.setLineWidth(1); //表盘线的粗细
ctx.setStrokeStyle('#9f9f9f'); //表盘线的颜色
ctx.stroke();
// 绘制时钟刻度
for (let i = 0; i < 12; i++) {
const angle = i * (Math.PI / 6) - Math.PI / 2;
const x = 45 + Math.cos(angle) * 36; //时钟刻度X轴位置
const y = 45 + Math.sin(angle) * 36; //时钟刻度Y轴位置
ctx.beginPath();
ctx.arc(x, y, 1, 0, 2 * Math.PI); //第三个参数为大小
ctx.setFillStyle('#000'); //时钟刻度颜色
ctx.fill();
}
// 获取当前时间
const now = new Date();
const hours = now.getHours();
const minutes = now.getMinutes();
const seconds = now.getSeconds();
// 绘制时针
const hourAngle = (hours % 12 + minutes / 60 + seconds / 3600) * (Math.PI / 6) - Math.PI / 2;
const hourX = 45 + Math.cos(hourAngle) * 24; //时针X轴位置
const hourY = 45 + Math.sin(hourAngle) * 24; //时针Y轴位置
ctx.beginPath();
ctx.setLineWidth(2); //时针的粗细
ctx.setStrokeStyle('#000'); //时针颜色
ctx.moveTo(45, 45); //时针围绕中心点
ctx.lineTo(hourX, hourY);
ctx.stroke();
// 绘制分针
const minuteAngle = (minutes + seconds / 60) * (Math.PI / 30) - Math.PI / 2;
const minuteX = 45 + Math.cos(minuteAngle) * 33; //分针X轴位置
const minuteY = 45 + Math.sin(minuteAngle) * 33; //分针Y轴位置
ctx.beginPath();
ctx.setLineWidth(1.5); //分针的粗细
ctx.setStrokeStyle('#000'); //分针颜色
ctx.moveTo(45, 45); //分针围绕中心点
ctx.lineTo(minuteX, minuteY);
ctx.stroke();
// 绘制秒针
const secondAngle = (seconds + now.getMilliseconds() / 1000) * (Math.PI / 30) - Math.PI / 2;
const secondX = 45 + Math.cos(secondAngle) * 36; //分针X轴位置
const secondY = 45 + Math.sin(secondAngle) * 36; //分针Y轴位置
ctx.beginPath();
ctx.setLineWidth(1); //分针的粗细
ctx.setStrokeStyle('#f00'); //分针颜色
ctx.moveTo(45, 45); //分针围绕中心点
ctx.lineTo(secondX, secondY);
ctx.stroke();
ctx.draw();
},
},
beforeDestroy() {
this.stopClock();
}
};
</script>
<style>
.container {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
height: 100vh;
}
.clock {
width: 300px;
height: 300px;
}
</style>
想要修改样式,在代码中有注释,基本上要修改的就是大小,及其颜色,都有备注,需要改动的话尽量固定所改动的比例关系