Canvas 時鐘
在這些章節中,我們將使用 HTML canvas 來構建一個模擬時鐘。
第一部分 - 建立 Canvas
時鐘需要一個 HTML 容器。建立一個 HTML canvas
HTML 程式碼
<!DOCTYPE html>
<html>
<body>
<canvas id="canvas" width="400" height="400" style="background-color:#333"></canvas>
<script>
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
let radius = canvas.height / 2;
ctx.translate(radius, radius);
radius = radius * 0.90
drawClock();
function drawClock() {
ctx.arc(0, 0, radius, 0 , 2 * Math.PI);
ctx.fillStyle = "white";
ctx.fill();
}
</script>
</body>
</html>
自己動手試一試 »
程式碼解釋
在頁面中新增一個 HTML <canvas> 元素
<canvas id="canvas" width="400" height="400" style="background-color:#333"></canvas>
建立一個 canvas 物件 (const canvas) 來引用 HTML canvas 元素
const canvas = document.getElementById("canvas");
為 canvas 物件建立一個 2d 繪圖物件 (const ctx)
const ctx = canvas.getContext("2d");
計算時鐘的半徑,使用 canvas 的高度
let radius = canvas.height / 2;
注意
使用 canvas 的高度來計算時鐘半徑,可以使時鐘適用於所有 canvas 大小。
重新對映 (0,0) 的位置(繪圖物件)到 canvas 的中心
ctx.translate(radius, radius);
減小時鐘半徑(到 90%),以便在 canvas 中更好地繪製時鐘
radius = radius * 0.90;
建立一個函式來繪製時鐘
function drawClock() {
ctx.arc(0, 0, radius, 0 , 2 * Math.PI);
ctx.fillStyle = "white";
ctx.fill();
}