Canvas绘制动态时钟

2020-01-29  本文已影响0人  learninginto

Canvas绘制动态时钟

<canvas id="canvas" width="500" height="500"></canvas>
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext("2d");

function draw(x, y, r) {
    ctx.clearRect(0, 0, canvas.width, canvas.height);

    var d = new Date();
    var h = d.getHours();
    var m = d.getMinutes();
    var s = d.getSeconds();
    var ms = d.getTime();

    // 分针走过的角度要加上 秒针走过角度 / 60 * 6)
    var mdeg = (m * 6 - 90 + s / 60 * 6) * Math.PI / 180;

    // 时针走过的角度(要加上 分针走过角度 / 60 * 30)
    var hdeg = (h * 30 - 90 + m / 60 * 30) * Math.PI / 180;
    var sdeg = (ms / 1000 % 60 * 6 - 90) * Math.PI / 180;

    //绘制分钟的刻度
    for (var i = 0; i < 60; i++) {
        ctx.beginPath();
        ctx.moveTo(x, y);
        ctx.arc(x, y, r, (i * 6) * Math.PI / 180, (i + 1) * 6 * Math.PI / 180);
        ctx.closePath();
        ctx.stroke();
    }

    //绘制盖住分钟内圆刻度的白圆
    ctx.beginPath();
    ctx.fillStyle = "white";
    ctx.arc(x, y, r * 14 / 15, 0, 2 * Math.PI);
    ctx.fill();
    ctx.closePath();

    //绘制小时的刻度
    for (var i = 0; i < 12; i++) {
        ctx.beginPath();
        ctx.moveTo(x, y);
        ctx.arc(x, y, r, (i * 30) * Math.PI / 180, (i + 1) * 30 * Math.PI / 180);
        ctx.closePath();
        ctx.stroke();
    }

    //绘制盖住小时刻度的白圆
    ctx.beginPath();
    ctx.fillStyle = "white";
    ctx.arc(x, y, r * 13 / 15, 0, 2 * Math.PI);
    ctx.fill();
    ctx.closePath();

    //绘制时针
    ctx.beginPath();
    ctx.save();
    ctx.moveTo(x, y);
    ctx.lineWidth = 5;
    ctx.arc(x, y, r * 2 / 5, hdeg, hdeg);
    ctx.stroke();
    ctx.restore();
    ctx.closePath();

    //绘制分针
    ctx.beginPath();
    ctx.save();
    ctx.moveTo(x, y);
    ctx.lineWidth = 3;
    ctx.arc(x, y, r * 3 / 5, mdeg, mdeg);
    ctx.stroke();
    ctx.restore();
    ctx.closePath();

    //绘制秒针
    ctx.beginPath();
    ctx.save();
    ctx.moveTo(x, y);
    ctx.lineWidth = 2;
    ctx.arc(x, y, r * 4 / 5, sdeg, sdeg);
    ctx.stroke();
    ctx.restore();
    ctx.closePath();

    // 绘制圆心
    ctx.beginPath();
    ctx.save();
    ctx.moveTo(x, y);
    ctx.arc(x, y, r * 1 / 28, 0, 2 * Math.PI);
    ctx.fillStyle = "red";
    ctx.fill();
    ctx.restore();
    ctx.closePath();
}

draw(240, 240, 200);

setInterval(function(){
    draw(240, 240, 200);
},16)
上一篇 下一篇

猜你喜欢

热点阅读