使用 canvas画时钟

今天看了H5的canvas,练习使用下。待完善。。。

class Clock {
    constructor(canvas) {
        this.canvas = canvas;
    }

    draw() {
        let ctx = this.canvas.getContext("2d");
        
        ctx.setDefault = function() {
            const default_strokeStyle = "#000000";
            this.strokeStyle = default_strokeStyle; 
        }

        this.drawClockDialPlate(ctx);
        this.drawClockDial(ctx);

    }

    // 画表盘
    drawClockDialPlate(ctx) {
        ctx.beginPath();
        ctx.strokeStyle = "blue";
        ctx.lineWidth = 2;
        ctx.arc(400, 300, 200, 0, Math.PI*2, false);
        ctx.stroke();

        ctx.setDefault();
    }

    // 画刻度盘
    drawClockDial(ctx) {

        ctx.beginPath();
        ctx.translate(400, 300);
        ctx.lineWidth = 1;

        let scale = 30; // 每一小时对应30度

        let rg = ctx.createRadialGradient(0, 0, 180, 0, 0, 185);
        rg.addColorStop(0.9, this.canvas.style.backgroundColor);
        rg.addColorStop(1, "blue");
        ctx.strokeStyle = rg;

        for (let an = 0; an < 360; an += scale) {

            // 先画再转
            ctx.moveTo(0, 0);
            ctx.lineTo(200, 0);
            ctx.rotate(scale * Math.PI / 180);
        }

        ctx.stroke();

        // 重复画会导致小时刻度不明显
        ctx.beginPath();
        scale = 6; // 每一分钟对应6度
        rg = ctx.createRadialGradient(0, 0, 190, 0, 0, 195);
        rg.addColorStop(0.9, this.canvas.style.backgroundColor);
        rg.addColorStop(1, "blue");
        ctx.strokeStyle = rg;
        
        for (let an = 0; an < 360; an += scale) {
 
            // 重复画会导致小时刻度不明显
            if (an % 30 !== 0) { 
                ctx.moveTo(0, 0);
                ctx.lineTo(200, 0);
            }

            ctx.rotate(scale * Math.PI / 180);

        }
        
        ctx.stroke();

        ctx.setDefault();
        ctx.translate(-400, -300); // 还原
    }

}

let canvas = document.createElement("canvas");
let style = canvas.style;
[canvas.width, canvas.height] = [800, 600];
[style.backgroundColor, style.position, style.zIndex] = ["green", "absolute", 1]
document.body.prepend(canvas);

new Clock(canvas).draw();

 使用 canvas画时钟

相关推荐