看懂当前时钟案例需要有一定canvas基础!
绘制时钟
<body>
<canvas id="canvas" width="500" height="500"></canvas>
</body>
1、绘制表盘
const c = document.querySelector('#canvas');
const ctx = c.getContext("2d");
const r = 200;
ctx.translate(250, 250);
initClock();
function initClock() {
ctx.beginPath();
ctx.lineWidth = 6;
ctx.arc(0, 0, r, 0, 2 * Math.PI, false);
ctx.stroke();
drawClockLine();
drawClockText();
}
2、绘制刻度
function drawClockLine() {
for (let i = 0; i < 60; i++) {
const radian = 360 / 60 * i * Math.PI / 180;
ctx.beginPath();
ctx.save();
ctx.rotate(radian);
ctx.moveTo(r, 0);
ctx.lineWidth = 3;
ctx.lineCap = "round";
ctx.lineTo(190, 0);
if (i % 5 === 0) {
ctx.lineWidth = 6;
ctx.lineTo(182, 0);
}
ctx.stroke();
ctx.restore();
}
}
3、绘制文本
function drawClockText() {
const textList = ["Ⅲ", "Ⅳ", "Ⅴ", "Ⅵ", "Ⅶ", "Ⅷ", "Ⅸ", "Ⅹ", "Ⅺ", "Ⅻ", "Ⅰ", "Ⅱ"]
for (let j = 0; j < 12; j++) {
let radian = 360 / 12 * j * Math.PI / 180;
let x = (r - 35) * Math.cos(radian);
let y = (r - 35) * Math.sin(radian);
ctx.font = "18px Arial";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillStyle = "black";
ctx.fillText(textList[j], x, y);
}
const NAME = "Daniel Wellington";
ctx.textAlign = "center";
ctx.fillText(NAME, 0, -100);
}
dot();
function dot() {
ctx.beginPath();
ctx.moveTo(0, 0);
ctx.fillStyle = "red";
ctx.arc(0, 0, 4, 0, 2 * Math.PI, false);
ctx.fill();
}
4、绘制表针
function drawHourLine() {
const today = new Date();
let hour = today.getHours();
const minutes = today.getMinutes();
if (hour > 12) {
hour = hour - 12;
}
const minuteRadian = 30 / 60 * minutes * Math.PI / 180;
const hourRadian = 30 * hour * Math.PI / 180;
drawTimeLine("black", minuteRadian + hourRadian, 8, 20, -145);
}
function drawMinuteLine() {
const today = new Date();
const minutes = today.getMinutes();
const radian = 6 * minutes * Math.PI / 180;
drawTimeLine("red", radian, 4, 25, -160);
}
function drawSecondLine() {
const today = new Date();
const seconds = today.getSeconds();
const radian = 6 * seconds * Math.PI / 180;
drawTimeLine("blue", radian, 2, 30, -170);
}
function drawTimeLine(color, radian, lineWidth, y1, y2) {
ctx.save();
ctx.rotate(radian);
ctx.beginPath();
ctx.moveTo(0, y1);
ctx.lineTo(0, y2);
ctx.lineWidth = lineWidth;
ctx.lineCap = "round";
ctx.strokeStyle = color;
ctx.stroke();
ctx.restore();
}
5、表针动画
handleAllTimeLine();
function handleAllTimeLine() {
drawHourLine();
drawMinuteLine();
drawSecondLine();
}
setInterval(() => {
ctx.clearRect(-210, -210, 450, 450);
handleAllTimeLine();
initClock();
dot();
}, 1000);
|