MDN의 시계 예제를 를 보고 따라서 만들어 봤습니다. 코드를 좀 개선해봤는데, 어떤지는 모르겠네요. 🙃
<!DOCTYPE html>
<canvas id="canvas1" width="150" height="150"></canvas>
<script>
var canvas = document.getElementById("canvas1");
var ctx = canvas.getContext("2d");
var back = document.createElement("canvas");
back.width = back.height = 150;
var oldSec = -1;
function drawLine(ctx, x1, x2) {
ctx.beginPath();
ctx.moveTo(x1, 0);
ctx.lineTo(x2, 0);
ctx.stroke();
}
function drawBackImage() {
var ctx = back.getContext("2d");
ctx.fillStyle = "white";
ctx.fillRect(0, 0, back.width, back.height);
ctx.translate(75, 75);
ctx.lineCap = "round";
// 분 눈금
ctx.lineWidth = 1.5;
for (var i = 0; i < 60; i++) {
ctx.rotate(Math.PI / 30);
drawLine(ctx, 48, 50);
}
// 시간 눈금
ctx.lineWidth = 3;
for (var i = 0; i < 12; i++) {
ctx.rotate(Math.PI / 6);
drawLine(ctx, 44, 50);
}
// 테두리
ctx.lineWidth = 6;
ctx.strokeStyle = "royalblue";
ctx.beginPath();
ctx.arc(0, 0, 60, 0, Math.PI * 2);
ctx.stroke();
}
function drawClockHands(hour, min, sec) {
ctx.save();
ctx.lineCap = "round";
ctx.translate(75, 75);
ctx.rotate(-Math.PI / 2);
// hour
ctx.save();
ctx.lineWidth = 5;
ctx.rotate((hour * Math.PI / 6) + (min * Math.PI / 360));
drawLine(ctx, -7, 35);
ctx.restore();
// minute
ctx.save();
ctx.lineWidth = 3.5;
ctx.rotate((min * Math.PI / 30) + (sec * Math.PI / 1800));
drawLine(ctx, -10, 47);
ctx.restore();
// second
ctx.save();
ctx.lineWidth = 2;
ctx.strokeStyle = ctx.fillStyle = "tomato";
ctx.rotate(sec * Math.PI / 30);
drawLine(ctx, -10, 38);
ctx.beginPath();
ctx.arc(0, 0, 4, 0, Math.PI * 2);
ctx.fill();
ctx.beginPath();
ctx.arc(42, 0, 3.5, 0, Math.PI * 2);
ctx.stroke();
ctx.restore();
ctx.restore();
}
function clock() {
var now = new Date();
var hour = now.getHours();
if (hour >= 12) hour -= 12;
var min = now.getMinutes();
var sec = now.getSeconds();
if (sec != oldSec) {
ctx.drawImage(back, 0, 0);
drawClockHands(hour, min, sec);
oldSec = sec;
}
requestAnimationFrame(clock);
}
drawBackImage();
clock();
</script>