自己写个时钟,通过动画实现指针旋转,直到今天结束。
表盘通过canvas画出来,指针为div元素,通过时间的计算,给指针添加旋转动画。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>今日时钟</title>
</head>
<style>
.container {
width: 400px;
padding: 40px;
margin: auto;
display: flex;
justify-content: center;
align-items: center;
}
.circle {
width: 200px;
height: 200px;
position: relative;
}
.point {
width: 2px;
background-color: #000000;
position: absolute;
top: 10px;
left: 99px;
transform-origin: bottom center;
}
.point.s {
height: 90px;
top: 10px;
opacity: 0.8;
z-index: 3;
}
.point.m {
height: 75px;
top: 25px;
opacity: 0.9;
z-index: 2;
background-color: red;
}
.point.h {
height: 60px;
top: 40px;
z-index: 1;
background-color: aqua;
}
.btn {
margin: auto;
text-align: center;
}
</style>
<script>
function drawNum(ctx, n) {
// 记录下原始状态
ctx.save();
const deg = n * Math.PI / 6;
ctx.moveTo(100 + 98 * Math.sin(deg), 100 - 98 * Math.cos(deg));
ctx.lineTo(100 + 90 * Math.sin(deg), 100 - 90 * Math.cos(deg));
ctx.stroke();
ctx.translate(100 + 90 * Math.sin(deg), 100 - 90 * Math.cos(deg));
ctx.rotate(deg);
ctx.font = "10px Arial";
ctx.fillText(n, n > 9 ? - 6 : -3, 10);
ctx.rotate(-deg);
ctx.translate(0, 0);
// 调整完坐标以及旋转角度后,还原状态
ctx.restore();
}
function draw() {
const ctx = document.getElementById("clock").getContext("2d");
ctx.beginPath();
ctx.lineWidth = 2;
// 先画表盘
ctx.arc(100, 100, 98, 0, 2 * Math.PI);
ctx.stroke();
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12].forEach(n => {
// 画刻度以及对应的数字
drawNum(ctx, n);
})
}
function runTime(cn, num, t) {
const obj = { s: 60, m: 60 * 60, h: 60 * 60 * 12 }
const duration = 1000 * num;
const deg = num / obj[t] * 360;
document.querySelector(cn).animate([
{
transform: `rotate(-${deg}deg)`,
},
{
transform: 'none'
}
], {
duration,
easing: 'linear',
fill: 'both',
})
}
function run() {
const d = new Date();
const t = 24 * 60 * 60;
const s = d.getSeconds();
const m = d.getMinutes();
const h = d.getHours();
// 计算今天剩余的时间(S)对指针添加动画
runTime('.point.s', t - s - m * 60 - h * 60 * 60, 's');
runTime('.point.m', t - s - m * 60 - h * 60 * 60, 'm');
runTime('.point.h', t - s - m * 60 - h * 60 * 60, 'h');
}
window.onload = () => {
// 画时钟
draw();
};
</script>
<body>
<div class="container">
<div class="circle">
<canvas width="200" height="200" id="clock"></canvas>
<div class="point s"></div>
<div class="point m"></div>
<div class="point h"></div>
</div>
</div>
<div class="btn">
<button onclick="run()">start</button>
</div>
</body>
</html>