js实现钟
以下是使用JavaScript实现一个动态时钟的几种方法,分为基础版和进阶版,代码可直接运行:
基础版:数字时钟
<div id="clock"></div>
<script>
function updateClock() {
const now = new Date();
const hours = now.getHours().toString().padStart(2, '0');
const minutes = now.getMinutes().toString().padStart(2, '0');
const seconds = now.getSeconds().toString().padStart(2, '0');
document.getElementById('clock').textContent = `${hours}:${minutes}:${seconds}`;
}
setInterval(updateClock, 1000);
updateClock(); // 立即执行一次避免初始空白
</script>
进阶版:模拟钟表(Canvas绘制)
<canvas id="analogClock" width="200" height="200"></canvas>
<script>
const canvas = document.getElementById('analogClock');
const ctx = canvas.getContext('2d');
const radius = canvas.height / 2;
function drawClock() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
const now = new Date();
// 绘制表盘
ctx.beginPath();
ctx.arc(radius, radius, radius - 5, 0, 2 * Math.PI);
ctx.strokeStyle = '#333';
ctx.lineWidth = 3;
ctx.stroke();
// 绘制刻度
for (let i = 0; i < 12; i++) {
const angle = i * Math.PI / 6;
ctx.lineWidth = i % 3 === 0 ? 3 : 1;
ctx.beginPath();
const x1 = radius + Math.sin(angle) * (radius - 10);
const y1 = radius - Math.cos(angle) * (radius - 10);
const x2 = radius + Math.sin(angle) * (radius - 20);
const y2 = radius - Math.cos(angle) * (radius - 20);
ctx.moveTo(x1, y1);
ctx.lineTo(x2, y2);
ctx.stroke();
}
// 绘制时针
const hour = now.getHours() % 12;
const hourAngle = (hour * Math.PI / 6) + (now.getMinutes() * Math.PI / 360);
drawHand(hourAngle, radius * 0.5, 5);
// 绘制分针
const minuteAngle = now.getMinutes() * Math.PI / 30;
drawHand(minuteAngle, radius * 0.7, 3);
// 绘制秒针
const secondAngle = now.getSeconds() * Math.PI / 30;
drawHand(secondAngle, radius * 0.9, 1);
}
function drawHand(angle, length, width) {
ctx.strokeStyle = width === 1 ? 'red' : '#333';
ctx.lineWidth = width;
ctx.beginPath();
ctx.moveTo(radius, radius);
ctx.lineTo(
radius + Math.sin(angle) * length,
radius - Math.cos(angle) * length
);
ctx.stroke();
}
setInterval(drawClock, 1000);
drawClock();
</script>
可选优化方向
-
添加日期显示:在数字时钟中扩展日期显示
const options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' }; const dateString = now.toLocaleDateString(undefined, options); -
样式美化:为数字时钟添加CSS样式
#clock { font-family: 'Arial', sans-serif; font-size: 3em; text-align: center; color: #333; background: #f0f0f0; padding: 20px; border-radius: 10px; } -
时区支持:通过
toLocaleTimeString()实现多时区显示
new Date().toLocaleTimeString('en-US', { timeZone: 'America/New_York' });






