Canvas时钟案例

174 阅读1分钟
// 获取 Canvas
/** @type {HTMLCanvasElement} */
let Canvas = document.getElementById("Canvas");
// 创建一个画布
let ctx = Canvas.getContext('2d');

// 绘制中心点
const initCentre = function initCentre() {
    // 画中心点
    ctx.beginPath();
    ctx.save()
    ctx.translate(450,300);
    ctx.arc(0, 0, 10, 0, Math.PI * 2);
    ctx.fill();
    ctx.restore()
}

// 绘制表盘
const initPlate = function initPlate() {
    // 开始绘制
    ctx.beginPath();
    ctx.save()
    ctx.lineWidth = 5;
    // 中心点
    ctx.translate(450, 300);
    // 画圆
    ctx.arc(0, 0, 200, 0, Math.PI * 2);
    // 绘制
    ctx.stroke();
}

// 绘制表盘刻度
const initScale = function initScale() {
    // 绘制数字
    ctx.beginPath();
    let scaleArr = [3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 1, 2];
    ctx.textAlign = 'center';
    ctx.textBaseline = 'middle';
    ctx.font = "15px Arial";
    scaleArr.forEach((item, i) => {
        let x = 175 * Math.cos((Math.PI * 2) / 12 * i),
            y = 175 * Math.sin((Math.PI * 2) / 12 * i);
        ctx.fillText(item, x, y);
    })
    ctx.stroke();

    // 绘制小点
    ctx.beginPath();
    let i = 0;
    for (; i < 60; i++) {
        ctx.beginPath();
        let x = 190 * Math.cos((Math.PI * 2) / 60 * i),
            y = 190 * Math.sin((Math.PI * 2) / 60 * i);
        i % 5 == 0 ? ctx.arc(x, y, 4, 0, Math.PI * 2) : ctx.arc(x, y, 2, 0, Math.PI * 2);
        ctx.fill();
    }
}

// 绘制时钟 分 秒 针
const drawHours = function drawHours(h, m) {
    let angle = (Math.PI * 2 / 12 * h) + (Math.PI * 2 / 12 / 60 * m) || 0;
    ctx.beginPath();
    ctx.rotate(angle);
    ctx.strokeStyle = "pink"
    ctx.lineWidth = 7;
    ctx.moveTo(0, 0);
    ctx.lineTo(0, -100);
    ctx.stroke();
    ctx.restore()
}

const drawMinute = function drawMinute(m) {
    let angle = (Math.PI * 2 / 60 * m) || 0;
    ctx.save();
    ctx.beginPath();
    ctx.rotate(angle);
    ctx.strokeStyle = "red"
    ctx.lineWidth = 5;
    ctx.moveTo(0, 0);
    ctx.lineTo(0, -130);
    ctx.stroke();
    ctx.restore()
}

const drawSecond = function drawSecond(s) {
    let angle = (Math.PI * 2 / 60 * s) || 0;
    ctx.save();
    ctx.beginPath();
    ctx.rotate(angle);
    ctx.strokeStyle = "yellow"
    ctx.lineWidth = 3;
    ctx.moveTo(0, 0);
    ctx.lineTo(0, -150);
    ctx.stroke();
    ctx.restore()
}

// 启动
function start() {
    setInterval(() => {
        ctx.clearRect(0, 0, 900, 600)
        let date = new Date(),
            h = date.getHours(),
            m = date.getMinutes(),
            s = date.getSeconds();
        initPlate();
        initScale();
        drawSecond(s);
        drawMinute(m);
        drawHours(h, m);
        initCentre();
    }, 1000)
}

start()