캔버스 시계 바늘
파트 IV - 시계 바늘 그리기
시계는 손이 필요합니다. 시계 바늘을 그리는 JavaScript 함수를 만듭니다.
자바스크립트:
function drawClock() {
drawFace(ctx, radius);
drawNumbers(ctx, radius);
drawTime(ctx, radius);
}
function drawTime(ctx, radius){
var now = new Date();
var hour = now.getHours();
var minute = now.getMinutes();
var second = now.getSeconds();
//hour
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 = (minute*Math.PI/30)+(second*Math.PI/(30*60));
drawHand(ctx, minute, radius*0.8, radius*0.07);
// second
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);
}
예시 설명
날짜를 사용하여 시, 분, 초를 가져옵니다.
var now = new Date();
var hour = now.getHours();
var minute = now.getMinutes();
var 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() 루틴은 설명이 필요하지 않습니다. 주어진 길이와 너비로 선을 그립니다.