Canvas 시계 지시针

제4부 - 시계 지시자 그리기

시계는 지시자가 필요합니다. 시계 지시자를 그리는 JavaScript 함수를 생성합니다:

JavaScript:

function drawClock() {
  drawFace(ctx, radius);
  drawNumbers(ctx, radius);
  drawTime(ctx, radius);
}
function drawTime(ctx, radius) {
  const now = new Date();
  let hour = now.getHours();
  let minute = now.getMinutes();
  let second = now.getSeconds();
  // 시
  hour = hour%12;
  hour = (hour*Math.PI/6)+(minute*Math.PI/(6*60))+(second*Math.PI/(360*60));
  drawHand(ctx, hour, radius*0.5, radius*0.07);
  // 분
  minute = (minute*Math.PI/30)+(second*Math.PI/(30*60));
  drawHand(ctx, minute, radius*0.8, radius*0.07);
  // 초
  second = (second*Math.PI/30);
  drawHand(ctx, second, radius*0.9, radius*0.02);
}
function drawHand(ctx, pos, length, width) {
  ctx.beginPath();
  ctx.lineWidth = width;
  ctx.lineCap = "round";
  ctx.moveTo(0,0);
  ctx.rotate(pos);
  ctx.lineTo(0, -length);
  ctx.stroke();
  ctx.rotate(-pos);
}

직접 시도해보세요

코드 설명

시간, 분, 초를 가져오기 위해 Date 객체를 생성합니다:

const now = new Date();
let hour = now.getHours();
let minute = now.getMinutes();
let second = now.getSeconds();

시침의 각도를 계산하고 그 길이(반지름의 50%)와 너비(반지름의 7%)를 그립니다:

hour = hour%12;
hour = (hour*Math.PI/6)+(minute*Math.PI/(6*60))+(second*Math.PI/(360*60));
drawHand(ctx, hour, radius*0.5, radius*0.07);

같은 기술을 사용하여 시침과 분침을 그립니다.

drawHand() 절차는 설명이 필요 없습니다. 그것이 그려주는 것은 주어진 길이와 너비의 선입니다.

다른 참조:

CodeW3C.com의 완전한 Canvas 참조 매뉴얼