使用svg画出一个时钟
<!DOCTYPE html>
<html>
<head>
<title>SVG Clock</title>
</head>
<body>
<svg width="200" height="200" viewBox="-100 -100 200 200">
<circle cx="0" cy="0" r="95" fill="white" stroke="black" stroke-width="5"/>
<circle cx="0" cy="0" r="5" fill="black"/>
<g id="hands">
<line id="hour" x1="0" y1="0" x2="0" y2="-50" stroke="black" stroke-width="4" stroke-linecap="round"/>
<line id="minute" x1="0" y1="0" x2="0" y2="-70" stroke="black" stroke-width="3" stroke-linecap="round"/>
<line id="second" x1="0" y1="0" x2="0" y2="-80" stroke="red" stroke-width="2" stroke-linecap="round"/>
</g>
<g id="numbers">
<text x="0" y="-80" text-anchor="middle" dominant-baseline="middle" font-size="12">12</text>
<text x="70" y="0" text-anchor="middle" dominant-baseline="middle" font-size="12">3</text>
<text x="0" y="80" text-anchor="middle" dominant-baseline="middle" font-size="12">6</text>
<text x="-70" y="0" text-anchor="middle" dominant-baseline="middle" font-size="12">9</text>
</g>
</svg>
<script>
function updateClock() {
const now = new Date();
const hours = now.getHours() % 12;
const minutes = now.getMinutes();
const seconds = now.getSeconds();
const hourHand = document.getElementById('hour');
const minuteHand = document.getElementById('minute');
const secondHand = document.getElementById('second');
const hourRotation = (hours * 30) + (minutes / 2); // 360 / 12 = 30 degrees per hour + minutes/2 for precision
const minuteRotation = minutes * 6; // 360 / 60 = 6 degrees per minute
const secondRotation = seconds * 6; // 360 / 60 = 6 degrees per second
hourHand.setAttribute('transform', `rotate(${hourRotation})`);
minuteHand.setAttribute('transform', `rotate(${minuteRotation})`);
secondHand.setAttribute('transform', `rotate(${secondRotation})`);
}
setInterval(updateClock, 1000);
updateClock(); // Initial update
</script>
</body>
</html>
代码解释:
- SVG 结构: 使用
<svg>元素创建 SVG 画布,并设置viewBox属性以控制 SVG 的坐标系。 - 圆形: 使用两个
<circle>元素绘制表盘和中心点。 - 指针: 使用三个
<line>元素分别表示时针、分针和秒针,并设置不同的样式。stroke-linecap="round"使指针末端呈圆形。 - 数字: 使用
<text>元素添加数字,text-anchor和dominant-baseline属性用于控制文本的定位。 hands和numbers组: 使用<g>元素将指针和数字分组,方便后续操作。- JavaScript 更新: 使用
setInterval每秒调用updateClock函数更新指针的位置。 updateClock函数: 获取当前时间,计算指针的旋转角度,并使用setAttribute更新指针的transform属性。
关键改进:
viewBox属性: 使用viewBox使时钟居中,并更容易缩放。- 更精确的时针旋转: 将分钟数加入到时针旋转计算中,使时针的移动更精确。
- 数字: 添加了数字,使时钟更完整。
- 初始更新: 在页面加载时立即调用
updateClock函数,以显示初始时间。
这个改进后的代码创建了一个更完整、更精确的 SVG 时钟,并且代码结构更
浙公网安备 33010602011771号