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();
}