DIV CSS 佈局教程網

用 JavaScript + HTML5 Canvas 手繪時鐘
編輯:關於JavaScript     

Canvas 的 2D 繪圖 API 很適合拿來練手,而時鐘是經典題目:它同時用上了圓弧、文字置中、旋轉矩陣與定時刷新。以下拆解完整實作。

一、HTML 部分

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0,minimum-scale=1.0,maximum-scale=1.0">
<title>canvas繪圖</title>
</head>
<body onload="init()">
<canvas id="canvas" width="200px" height="200px"></canvas>
</body>
</html>

二、JavaScript 部分

function init() {
    var canvas = document.getElementById("canvas"),
        context = canvas.getContext("2d");

    setInterval(function () {
        draw(canvas, context);
    }, 1000);
}

function draw(canvas, context) {
    var x = canvas.width,
        y = canvas.height,
        r = Math.min(x / 2, y / 2);

    context.clearRect(0, 0, x, y);   // 清除上一輪的繪製結果

    // 1. 繪製鐘面底色
    context.fillStyle = "#f1f1f1";
    drawCircle(context, x, y, r);

    // 2. 繪製 1~12 的數字
    var tx = x / 2, ty = y / 2, tr = 0.8 * r;
    context.font = "bold 12px 微軟雅黑";
    context.fillStyle = "#000";
    drawText(context, "1",  tx + 0.5 * tr,  ty - 0.866 * tr);
    drawText(context, "2",  tx + 0.866 * tr, ty - 0.5 * tr);
    drawText(context, "3",  tx + tr,        ty);
    drawText(context, "4",  tx + 0.866 * tr, ty + 0.5 * tr);
    drawText(context, "5",  tx + 0.5 * tr,  ty + 0.866 * tr);
    drawText(context, "6",  tx,             ty + tr);
    drawText(context, "7",  tx - 0.5 * tr,  ty + 0.866 * tr);
    drawText(context, "8",  tx - 0.866 * tr, ty + 0.5 * tr);
    drawText(context, "9",  tx - tr,        ty);
    drawText(context, "10", tx - 0.866 * tr, ty - 0.5 * tr);
    drawText(context, "11", tx - 0.5 * tr,  ty - 0.866 * tr);
    drawText(context, "12", tx,             ty - tr);

    // 3. 取得當前時間,換算成弧度
    var date = new Date(),
        h = date.getHours(),
        m = date.getMinutes(),
        s = date.getSeconds(),
        angleH = (360 / 12) * Math.PI / 180,
        angleM = (360 / 60) * Math.PI / 180;

    context.strokeSyle = "#000";

    // 4. 繪製刻度:時刻度粗、分刻度細
    drawScale(context, x, y, r, angleH, -0.88 * r, -0.96 * r, 3);
    drawScale(context, x, y, r, angleM, -0.93 * r, -0.96 * r, 1);

    // 5. 繪製時、分、秒針
    drawCircle(context, x, y, 3);
    drawNeedle(context, x, y, r, h * angleH + m * angleM / 12, -0.5 * r);
    drawNeedle(context, x, y, r, m * angleM + s * angleM / 60, -0.6 * r);
    drawNeedle(context, x, y, r, s * angleM,                  -0.75 * r);
}

// 畫圓
function drawCircle(context, x, y, r) {
    context.save();
    context.beginPath();
    context.arc(x / 2, y / 2, r, 0, Math.PI * 2, 0);
    context.fill();
    context.closePath();
    context.restore();
}

// 畫文字(靠 measureText 做水平置中)
function drawText(context, text, x, y) {
    context.save();
    x -= (context.measureText(text).width / 2);
    y += 4;
    context.translate(x, y);
    context.fillText(text, 0, 0);
    context.restore();
}

// 畫刻度
function drawScale(context, x, y, r, rotate, start, end, lineWidth) {
    context.save();
    context.beginPath();
    context.translate(x / 2, y / 2);
    context.lineWidth = lineWidth;
    for (var i = 0; i < 60; i++) {
        context.rotate(rotate);
        context.moveTo(0, start);
        context.lineTo(0, end);
    }
    context.closePath();
    context.stroke();
    context.restore();
}

// 畫時分秒針
function drawNeedle(context, x, y, r, rotate, line) {
    context.save();
    context.translate(x / 2, y / 2);
    context.beginPath();
    context.rotate(rotate);
    context.moveTo(0, 0.1 * r);
    context.lineTo(0, line);
    context.closePath();
    context.stroke();
    context.restore();
}

三、幾個關鍵技巧

  • 用三角函數定位數字。圓周上任一點的座標是 (cx + R·cosθ, cy + R·sinθ)。程式碼中的 0.5 與 0.866 就是 30° 與 60° 的 sin/cos 值,乘上半徑再偏移圓心即可。
  • save() 與 restore() 成對出現。Canvas 的狀態(位移、旋轉、線寬、樣式)會互相影響,每次變換前 save、結束後 restore,才能避免污染後續繪製。
  • 用 rotate 畫刻度最省事。把原點移到圓心,然後迴圈 60 次、每次旋轉 6°,畫出的就是一圈均勻的刻度線。
  • 指針角度要考慮「進位」。分針的公式 m * angleM + s * angleM / 60 讓分針隨秒數平滑前進,時針也同理帶入分鐘,這樣指針才不會每分鐘「跳」一次。
  • 別忘了 clearRect。每次重繪前必須清畫布,否則會出現殘影。

順帶一提,原程式碼中 context.strokeSyle 是個拼字錯誤(正確應為 strokeStyle),實作時記得修正,否則線條顏色不會套用。

希望本文所述對大家 JavaScript 程式設計有所幫助。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved