canvas入门--绘制时钟

这篇博客展示了如何使用HTML5的Canvas元素和JavaScript来创建一个实时动态的时钟。通过JavaScript代码,实现了获取当前时间并绘制时针、分针和秒针的功能,同时还包括绘制表盘、刻度等细节,提供了完整的代码示例和运行效果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、Html代码:

 <canvas id="canvasFirst" width="800" height="600"></canvas>

2、JavaScript代码:

// 1、找到画布对象
var canvasFirst = document.getElementById("canvasFirst");
// 2、上下文对象(画笔)
var ctx = canvasFirst.getContext("2d");
setInterval(function () {
    renderClock();
}, 1000);
function renderClock() {
    ctx.clearRect(0, 0, 800, 600);
    ctx.save();
    // 将坐标移动到画布的坐标
    ctx.translate(400, 300);
    ctx.rotate((-2 * Math.PI) / 4);
    ctx.save();
    // 绘制表盘
    ctx.beginPath();
    ctx.arc(0, 0, 200, 0, 2 * Math.PI, false);
    ctx.strokeStyle = "darkgrey";
    ctx.lineWidth = 10;
    ctx.stroke();
    ctx.closePath();
    // 绘制分钟刻度
    for (var j = 0; j < 60; j++) {
        ctx.rotate(Math.PI / 30);
        ctx.beginPath();
        ctx.moveTo(188, 0);
        ctx.lineTo(195, 0);
        ctx.strokeStyle = "orangered";
        ctx.lineWidth = 2;
        ctx.stroke();
        ctx.closePath();
    }
    ctx.restore();
    ctx.save();
    // 绘制时钟刻度
    for (var i = 0; i < 12; i++) {
        ctx.rotate(Math.PI / 6);
        ctx.beginPath();
        ctx.moveTo(180, 0);
        ctx.lineTo(200, 0);
        ctx.lineWidth = 10;
        ctx.strokeStyle = "darkgrey";
        ctx.stroke();
        ctx.closePath();
    }
    ctx.restore();
    ctx.save();

    // 绘制时针秒针
    var time = new Date();
    var hour = time.getHours();
    var min = time.getMinutes();
    var sec = time.getSeconds();
    console.log(hour + ":" + min + " " + sec);
    // 如果时间大于12,直接减去12
    hour = hour > 12 ? hour - 12 : hour;

    // 绘制秒针
    ctx.beginPath();
    ctx.rotate(((2 * Math.PI) / 60) * sec);
    ctx.moveTo(-30, 0);
    ctx.lineTo(170, 0);
    ctx.lineWidth = 2;
    ctx.strokeStyle = "red";
    ctx.stroke();
    ctx.closePath();

    ctx.restore();
    ctx.save();

    // 绘制分针
    ctx.beginPath();
    ctx.rotate(((2 * Math.PI) / 60) * min + ((2 * Math.PI) / 3600) * sec);
    ctx.moveTo(-20, 0);
    ctx.lineTo(150, 0);
    ctx.lineWidth = 4;
    ctx.strokeStyle = "darkblue";
    ctx.stroke();
    ctx.closePath();

    ctx.restore();
    ctx.save();

    // 绘制分针
    ctx.beginPath();
    ctx.rotate(((2 * Math.PI) / 12) * hour + ((2 * Math.PI) / 60 / 12) * min);
    ctx.moveTo(-20, 0);
    ctx.lineTo(140, 0);
    ctx.lineWidth = 6;
    ctx.strokeStyle = "darkslategray";
    ctx.stroke();
    ctx.closePath();
      
    ctx.arc(0, 0, 10, 0, 2 * Math.PI);
    ctx.fillStyle = "deepskyblue";
    ctx.fill();

    ctx.restore();
    ctx.restore();
    ctx.save();
}

3、效果图:

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值