JS代码
let cavEles = document.getElementsByTagName("canvas");
// 画背景
let ctx1 = cavEles[0].getContext("2d");
//画时针
let ctx2 = cavEles[1].getContext("2d");
//获取尺寸
let { offsetWidth: w, offsetHeight: h } = cavEles[0];
//获取π
let { PI } = Math;
// 设置中心
ctx2.translate(w / 2, h / 2);
//背景
function bg(ctx, r) {
ctx.beginPath();
ctx.translate(w / 2, h / 2);
ctx.arc(0, 0, r, 0, 2 * PI);
ctx.strokeStyle = "#ddd";
ctx.lineWidth = 5;
ctx.stroke();
for (let i = 0; i < 60; i++) {
ctx.beginPath();
let y = i % 5 == 0 ? 4 : 6;
ctx.moveTo(0, -r + r / 15);
ctx.lineTo(0, -r + r / y);
ctx.rotate(6 * PI / 180);
ctx.strokeStyle = "#666";
ctx.lineWidth = 5;
ctx.stroke();
}
}
bg(ctx1, 150);
// 时针
function createPointer(ctx) {
let timer = new Date();
ctx.clearRect(-w, -h, 2 * w, 2 * h);
ctx.beginPath();
ctx.save();
ctx.arc(0, 0, 5, 0, 2 * PI);
ctx.fill();
// 秒针
ctx.save();
let seconds = timer.getSeconds();
let secondsRate = 360 / 60 * seconds; //角度计算
ctx.beginPath();
ctx.rotate(secondsRate * PI / 180);
ctx.moveTo(0, 0);
ctx.lineTo(0, -90);
ctx.lineWidth = 1;
ctx.strokeStyle = "gray";
ctx.stroke();
ctx.restore();
// 分针
// 获取当前时间分针角度
ctx.save();
let minutes = timer.getMinutes();
let minutesRate = 360 / 60 * minutes + secondsRate / 60;
ctx.beginPath();
ctx.rotate(minutesRate * PI / 180);
ctx.moveTo(0, 0);
ctx.lineTo(0, -70);
ctx.lineWidth = 3;
ctx.strokeStyle = "red";
ctx.stroke();
ctx.restore();
// 时针
// 获取当前时间时针角度
let hour = timer.getHours();
let hourRate = 360 / 12 * hour + minutesRate / 12;
ctx.beginPath();
ctx.rotate(hourRate * PI / 180);
ctx.moveTo(0, 0);
ctx.lineTo(0, -60);
ctx.lineWidth = 5;
ctx.strokeStyle = "black";
ctx.stroke();
ctx.restore();
}
createPointer(ctx2);
setInterval(function () {
createPointer(ctx2);
}, 1000);
html代码
<style>
div {
width: 600px;
height: 400px;
border: 1px solid red;
margin: auto;
position: relative;
}
canvas {
position: absolute;
}
</style>
<div>
<canvas width="600" height="400"></canvas>
<canvas width="600" height="400"></canvas>
</div>