js实现时针
使用Canvas绘制时针
在HTML中创建Canvas元素,通过JavaScript获取上下文并绘制时针。
<canvas id="clock" width="200" height="200"></canvas>
<script>
const canvas = document.getElementById('clock');
const ctx = canvas.getContext('2d');
const centerX = canvas.width / 2;
const centerY = canvas.height / 2;
function drawHourHand(hours, minutes) {
const angle = (hours % 12 + minutes / 60) * Math.PI / 6 - Math.PI / 2;
const length = canvas.width / 3;
ctx.beginPath();
ctx.moveTo(centerX, centerY);
ctx.lineTo(
centerX + Math.cos(angle) * length,
centerY + Math.sin(angle) * length
);
ctx.lineWidth = 6;
ctx.strokeStyle = '#000';
ctx.stroke();
}
function updateClock() {
const now = new Date();
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawHourHand(now.getHours(), now.getMinutes());
requestAnimationFrame(updateClock);
}
updateClock();
</script>
使用SVG实现动态时针
通过SVG和JavaScript创建可动态更新的时针。

<svg id="clock" width="200" height="200" viewBox="0 0 200 200">
<circle cx="100" cy="100" r="95" fill="none" stroke="#000" stroke-width="2"/>
<line id="hourHand" x1="100" y1="100" x2="100" y2="50" stroke="#000" stroke-width="6" stroke-linecap="round"/>
</svg>
<script>
const hourHand = document.getElementById('hourHand');
const centerX = 100;
const centerY = 100;
function updateHourHand() {
const now = new Date();
const hours = now.getHours();
const minutes = now.getMinutes();
const angle = (hours % 12 + minutes / 60) * 30 - 90;
const length = 50;
const radian = angle * Math.PI / 180;
hourHand.setAttribute('x2', centerX + Math.cos(radian) * length);
hourHand.setAttribute('y2', centerY + Math.sin(radian) * length);
requestAnimationFrame(updateHourHand);
}
updateHourHand();
</script>
纯CSS动画时针
利用CSS transform和动画实现时针效果,通过JavaScript更新时间。

<div class="clock">
<div class="hour-hand"></div>
</div>
<style>
.clock {
width: 200px;
height: 200px;
border: 2px solid #000;
border-radius: 50%;
position: relative;
}
.hour-hand {
width: 6px;
height: 60px;
background: #000;
position: absolute;
left: 50%;
top: 50%;
transform-origin: bottom center;
margin-left: -3px;
border-radius: 3px;
}
</style>
<script>
const hourHand = document.querySelector('.hour-hand');
function updateClock() {
const now = new Date();
const hours = now.getHours();
const minutes = now.getMinutes();
const degrees = (hours % 12 + minutes / 60) * 30;
hourHand.style.transform = `rotate(${degrees}deg)`;
requestAnimationFrame(updateClock);
}
updateClock();
</script>
使用requestAnimationFrame优化性能
所有实现中都使用了requestAnimationFrame来实现平滑动画,这是浏览器推荐的动画实现方式,相比setInterval能提供更好的性能。
function animate() {
// 更新逻辑
requestAnimationFrame(animate);
}
animate();
考虑时区问题
如果需要处理不同时区,可以调整获取的小时数。
const now = new Date();
const hours = now.getHours() + timezoneOffset; // 时区偏移量
这些方法提供了从简单到复杂的时针实现方案,可以根据项目需求选择适合的方式。Canvas方案适合需要复杂绘制的场景,SVG方案便于维护和缩放,CSS方案性能较好且实现简单。





