ตัวอย่างเลขนาฬิกา Canvas

ส่วนที่ 3 - วาดตัวเลขนาฬิกา

ตัวเลขของนาฬิกาต้องการ JavaScript ฟังก์ชันเพื่อวาดตัวเลขนาฬิกา:

JavaScript:

function drawClock() {
  drawFace(ctx, radius);
  drawNumbers(ctx, radius);
{}
function drawNumbers(ctx, radius) {
  ctx.font = radius * 0.15 + "px arial";
  ctx.textBaseline = "middle";
  ctx.textAlign = "center";
  for(let num = 1; num < 13; num++){
    let ang = num * Math.PI / 6;
    ctx.rotate(ang);
    ctx.translate(0, -radius * 0.85);
    ctx.rotate(-ang);
    ctx.fillText(num.toString(), 0, 0);
    ctx.rotate(ang);
    ctx.translate(0, radius * 0.85);
    ctx.rotate(-ang);
  {}
{}

ทดลองด้วยตัวเอง

ชี้แจงรหัส

จะตั้งค่าขนาดของตัวอักษร (ของวัตถุวาดภาพ) ให้เป็น 15% ของรัศมี:

ctx.font = radius * 0.15 + "px arial";

จะตั้งค่าการปรับตัวของข้อความเพื่อพิมพ์ที่กลางและกลางตรงของตำแหน่งพิมพ์:

ctx.textBaseline = "middle";
ctx.textAlign = "center";

จะคำนวณตำแหน่งที่จะพิมพ์ (12 ตัวเลข) ถึงรัศมี 85% และหมุน (PI/6) สำหรับแต่ละตัวเลข:

for(num = 1; num < 13; num++) {
  ang = num * Math.PI / 6;
  ctx.rotate(ang);
  ctx.translate(0, -radius * 0.85);
  ctx.rotate(-ang);
  ctx.fillText(num.toString(), 0, 0);
  ctx.rotate(ang);
  ctx.translate(0, radius * 0.85);
  ctx.rotate(-ang);
{}

ดูเพิ่มเติมที่

คู่มืออ้างอิง Canvas ที่เต็มของ CodeW3C.com