แหล่งที่มานาฬิกา Canvas
- หน้าก่อน ตัวเลขนาฬิกา
- หน้าต่อไป เริ่มต้นนาฬิกา
ส่วนที่สี่ - วาดตัวชั่วโมง
ตัวชั่วโมงจำเป็นต้องมีแผ่นและแผ่นวินาที. สร้างฟังก์ชัน 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() กระบวนการไม่ต้องอธิบาย. มันวาดสายที่มีความยาวและความกว้างที่กำหนด
ดูเพิ่มเติม:
- หน้าก่อน ตัวเลขนาฬิกา
- หน้าต่อไป เริ่มต้นนาฬิกา