<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>时钟</title>
<link rel="stylesheet" href="./CSS/index.css">
</head>
<body>
<div>
<canvas width="600" height="400"></canvas>
<canvas width="600" height="400"></canvas>
</div>
<script src="../../../tools.js"></script>
<script src="./JS/index.js">`let canEles = document.querySelectorAll("canvas");
let bgctx = canEles[0].getContext("2d");
let pointerctx = canEles[1].getContext("2d");
let { offsetHeight: h, offsetWidth: w } = canEles[0];
let { PI } = Math;
//画表盘和刻度
function bg(pen, r, kedu) {
pen.save();
pen.beginPath();
pen.translate(w / 2, h / 2);
pen.arc(0, 0, r, 0, 2 * PI);
pen.lineWidth = 5;
// pen.strokeStyle = "#eee";
pen.stroke();
for (let index = 0; index < 60; index++) {
pen.beginPath();
let mx = index % 5 == 0 ? 50 : 30;
pen.moveTo(r - kedu, 0);
pen.lineTo(r - mx, 0);
pen.rotate(2 * PI / 60);
pen.lineWidth = 5;
pen.stroke();
}
}
//画时针、分针、秒针
function createPointer(pen) {
pen.save(); //时针、分针、秒针的开始
pen.clearRect(0, 0, w, h);
pen.beginPath();
pen.translate(w / 2, h / 2);
pen.arc(0, 0, 10, 0, 2 * PI);
pen.fill();
let timer = new Date();
//秒针
let seconds = timer.getSeconds(); //获取时针
//获取秒针的角度
let secondsRate = seconds / 60; //获取秒针的占比
let secondsAnlg = 2 * PI * secondsRate; //获取秒针的角度
pen.beginPath();
pen.save(); //秒针的开始
pen.rotate(secondsAnlg);
pen.moveTo(0, 0);
pen.lineTo(0, -80);
pen.strokeStyle = "blue";
pen.lineWidth = 1;
pen.stroke();
pen.restore(); //秒针的结束
//分针
let minutes = timer.getMinutes(); //获取分针
//获取分针的角度
let minutesRate = minutes / 60; //获取分针的占比
pen.save();
pen.beginPath();
pen.rotate(2 * PI * minutesRate + 2 * PI / 60 * secondsRate); //分针的角度
pen.moveTo(0, 0);
pen.lineTo(0, -70);
pen.strokeStyle = "red";
pen.lineWidth = 1;
pen.stroke();
pen.restore();
//时针
let hour = timer.getHours() % 12; //获取时针
//获取时针的角度
let hourRate = 2 * PI / 12;
pen.beginPath();
pen.save(); //时针开始
pen.rotate(hourRate * hour + 2 * PI / 12 * minutesRate); //时针的角度
pen.moveTo(0, 0);
pen.lineTo(0, -100);
pen.lineWidth = 5;
pen.stroke();
pen.restore(); //时针结束
pen.restore(); //时针、分针、秒针的开始
}
bg(bgctx, 150, 20);
createPointer(pointerctx);
//时钟动起来
setInterval(function () {
createPointer(pointerctx);
}, 1000);`</script>
</body>
</html>
div {
width: 600px;
height: 400px;
border: 1px solid red;
margin: auto;
position: relative;
}
canvas {
position: absolute;
top: 0;
left: 0;
}