Canvas时钟

JS代码

let cavEles = document.getElementsByTagName("canvas");
// 画背景
let ctx1 = cavEles[0].getContext("2d");
//画时针
let ctx2 = cavEles[1].getContext("2d");
//获取尺寸
let { offsetWidth: w, offsetHeight: h } = cavEles[0];
//获取π
let { PI } = Math;
// 设置中心
ctx2.translate(w / 2, h / 2);

//背景
function bg(ctx, r) {
    ctx.beginPath();
    ctx.translate(w / 2, h / 2);
    ctx.arc(0, 0, r, 0, 2 * PI);
    ctx.strokeStyle = "#ddd";
    ctx.lineWidth = 5;
    ctx.stroke();

    for (let i = 0; i < 60; i++) {
        ctx.beginPath();
        let y = i % 5 == 0 ? 4 : 6;
        ctx.moveTo(0, -r + r / 15);
        ctx.lineTo(0, -r + r / y);
        ctx.rotate(6 * PI / 180);
        ctx.strokeStyle = "#666";
        ctx.lineWidth = 5;
        ctx.stroke();
    }
}
bg(ctx1, 150);

// 时针
function createPointer(ctx) {
    let timer = new Date();
    ctx.clearRect(-w, -h, 2 * w, 2 * h);

    ctx.beginPath();
    ctx.save();
    ctx.arc(0, 0, 5, 0, 2 * PI);
    ctx.fill();

    // 秒针
    ctx.save();
    let seconds = timer.getSeconds();
    let secondsRate = 360 / 60 * seconds; //角度计算

    ctx.beginPath();
    ctx.rotate(secondsRate * PI / 180);
    ctx.moveTo(0, 0);
    ctx.lineTo(0, -90);
    ctx.lineWidth = 1;
    ctx.strokeStyle = "gray";
    ctx.stroke();
    ctx.restore();

    // 分针
    // 获取当前时间分针角度
    ctx.save();
    let minutes = timer.getMinutes();
    let minutesRate = 360 / 60 * minutes + secondsRate / 60;

    ctx.beginPath();
    ctx.rotate(minutesRate * PI / 180);
    ctx.moveTo(0, 0);
    ctx.lineTo(0, -70);
    ctx.lineWidth = 3;
    ctx.strokeStyle = "red";
    ctx.stroke();
    ctx.restore();

    // 时针
    // 获取当前时间时针角度
    let hour = timer.getHours();
    let hourRate = 360 / 12 * hour + minutesRate / 12;

    ctx.beginPath();
    ctx.rotate(hourRate * PI / 180);
    ctx.moveTo(0, 0);
    ctx.lineTo(0, -60);
    ctx.lineWidth = 5;
    ctx.strokeStyle = "black";
    ctx.stroke();
    ctx.restore();
}
createPointer(ctx2);

setInterval(function () {
    createPointer(ctx2);
}, 1000);

html代码

<style>
        div {
            width: 600px;
            height: 400px;
            border: 1px solid red;
            margin: auto;
            position: relative;
        }

        canvas {
            position: absolute;
        }
</style>
<div>
        <canvas width="600" height="400"></canvas>
        <canvas width="600" height="400"></canvas>
</div>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值