动态图片时钟是一种使用JavaScript和HTML5 Canvas来创建一个显示当前时间的时钟,其中时钟的每个数字或指针都是通过图片来表示的。这种时钟不仅可以显示时间,还可以通过动画效果使时钟看起来更加生动。
以下是一个简单的示例代码,展示如何使用JavaScript和HTML5 Canvas来实现一个动态的图片时钟。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Dynamic Image Clock</title>
<style>
canvas {
display: block;
margin: 50px auto;
background: #f0f0f0;
}
</style>
</head>
<body>
<canvas id="clockCanvas" width="400" height="400"></canvas>
<script src="clock.js"></script>
</body>
</html>
const canvas = document.getElementById('clockCanvas');
const ctx = canvas.getContext('2d');
const radius = canvas.height / 2;
ctx.translate(radius, radius);
const clockRadius = radius * 0.9;
function drawClock() {
drawFace(ctx, clockRadius);
drawNumbers(ctx, clockRadius);
drawTime(ctx, clockRadius);
}
function drawFace(ctx, radius) {
ctx.beginPath();
ctx.arc(0, 0, radius, 0, 2 * Math.PI);
ctx.fillStyle = 'white';
ctx.fill();
ctx.strokeStyle = '#333';
ctx.lineWidth = radius * 0.01;
ctx.stroke();
ctx.beginPath();
ctx.arc(0, 0, radius * 0.05, 0, 2 * Math.PI);
ctx.fillStyle = '#333';
ctx.fill();
}
function drawNumbers(ctx, radius) {
ctx.font = radius * 0.15 + "px arial";
ctx.textBaseline = "middle";
ctx.textAlign = "center";
for (let num = 1; num <= 12; num++) {
let ang = num * Math.PI / 6;
ctx.rotate(ang);
ctx.translate(0, -radius * 0.85);
ctx.rotate(-ang);
ctx.fillText(num.toString(), 0, 0);
ctx.rotate(ang);
ctx.translate(0, radius * 0.85);
ctx.rotate(-ang);
}
}
function drawTime(ctx, radius) {
const now = new Date();
let hour = now.getHours();
let minute = now.getMinutes();
let second = now.getSeconds();
// Hour
hour = hour % 12;
hour = (hour * Math.PI / 6) + (minute * Math.PI / (6 * 60)) + (second * Math.PI / (360 * 60));
drawHand(ctx, hour, radius * 0.5, radius * 0.07);
// Minute
minute = (minute * Math.PI / 30) + (second * Math.PI / (30 * 60));
drawHand(ctx, minute, radius * 0.8, radius * 0.07);
// Second
second = (second * Math.PI / 30);
drawHand(ctx, second, radius * 0.9, radius * 0.02);
}
function drawHand(ctx, pos, length, width) {
ctx.beginPath();
ctx.lineWidth = width;
ctx.lineCap = "round";
ctx.moveTo(0, 0);
ctx.rotate(pos);
ctx.lineTo(0, -length);
ctx.stroke();
ctx.rotate(-pos);
}
setInterval(drawClock, 1000);
setInterval
函数正确设置,并且每秒调用一次drawClock
函数。通过上述步骤和代码示例,你可以创建一个基本的动态图片时钟。根据需要,你可以进一步添加样式和功能,如不同的时钟背景、时间格式化选项等。
领取专属 10元无门槛券
手把手带您无忧上云