使用canvas绘制一个行走的时钟

在前端开发中,使用HTML5的<canvas>元素来绘制一个行走的时钟是一个很好的练习,它可以帮助你熟悉Canvas API以及基本的动画和数学原理。下面是一个简单的示例,展示了如何使用Canvas来创建一个简单的行走的时钟。

  1. HTML结构

首先,你需要在HTML文件中创建一个<canvas>元素。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>行走的时钟</title>
    <style>
        canvas {
            border: 1px solid black;
        }
    </style>
</head>
<body>
    <canvas id="clockCanvas" width="400" height="400"></canvas>
    <script src="clock.js"></script>
</body>
</html>
  1. JavaScript逻辑 (clock.js):

接下来,在clock.js文件中,你将编写JavaScript代码来绘制时钟并使其“行走”。

const canvas = document.getElementById('clockCanvas');
const ctx = canvas.getContext('2d');
const centerX = canvas.width / 2;
const centerY = canvas.height / 2;
const radius = 150;

function drawClockFace() {
    ctx.beginPath();
    ctx.arc(centerX, centerY, radius, 0, 2 * Math.PI);
    ctx.stroke();

    // 绘制小时标记
    for (let i = 0; i < 12; i++) {
        const x = centerX + radius * 0.8 * Math.cos((i * Math.PI) / 6 - Math.PI / 2);
        const y = centerY + radius * 0.8 * Math.sin((i * Math.PI) / 6 - Math.PI / 2);
        ctx.beginPath();
        ctx.moveTo(centerX, centerY);
        ctx.lineTo(x, y);
        ctx.stroke();
    }
}

function drawClockHands(hour, minute, second) {
    // 绘制时针
    const hourAngle = (hour % 12 + minute / 60) * (Math.PI / 6) - Math.PI / 2;
    drawHand(hourAngle, radius * 0.5, 'black');

    // 绘制分针
    const minuteAngle = (minute + second / 60) * (Math.PI / 30) - Math.PI / 2;
    drawHand(minuteAngle, radius * 0.7, 'blue');

    // 绘制秒针
    const secondAngle = second * (Math.PI / 30) - Math.PI / 2;
    drawHand(secondAngle, radius * 0.9, 'red');
}

function drawHand(angle, length, color) {
    ctx.beginPath();
    ctx.moveTo(centerX, centerY);
    ctx.lineTo(centerX + length * Math.cos(angle), centerY + length * Math.sin(angle));
    ctx.strokeStyle = color;
    ctx.lineWidth = 2;
    ctx.stroke();
}

function updateClock() {
    const now = new Date();
    const hour = now.getHours();
    const minute = now.getMinutes();
    const second = now.getSeconds();

    ctx.clearRect(0, 0, canvas.width, canvas.height); // 清除画布
    drawClockFace(); // 绘制时钟面
    drawClockHands(hour, minute, second); // 绘制时钟指针
}

// 初始绘制并启动时钟更新
updateClock();
setInterval(updateClock, 1000); // 每秒更新一次时钟

这段代码首先定义了画布和绘图上下文,然后定义了几个函数来绘制时钟的面和指针。updateClock函数负责根据当前时间更新时钟的显示。最后,通过调用updateClock函数并设置一个每秒执行一次的定时器来启动时钟的更新。

posted @   王铁柱6  阅读(5)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示