canvas 创作 表

用canvas 写的表
这里写图片描述

代码

1.初始化

const PI = Math.PI;
const center_x = 101;
const center_y = 101;
const o_circle_r = 100;
const i_circle_r = 90;
const log_r = 80;
const clock_num = ['Ⅰ', 'Ⅱ', 'Ⅲ', 'Ⅳ', 'Ⅴ', 'Ⅵ', 'Ⅶ', 'Ⅷ', 'Ⅸ', 'Ⅹ', 'Ⅺ', 'Ⅻ'];

2.表盘

function disk(ctx) {
    ctx.beginPath();
    ctx.arc(center_x, center_y, o_circle_r, 0, 2 * PI);
    ctx.fillStyle = "rgba(192,80,77,0.7)"
    ctx.fill();
    ctx.beginPath();
    ctx.arc(center_x, center_y, i_circle_r, 0, 2 * PI);
    ctx.fillStyle = "rgba(255,255,255,1)";
    ctx.fill();
    ctx.beginPath();
    ctx.arc(center_x, center_y, 1, 0, 2 * PI);
    ctx.fillStyle = "red";
    ctx.fill();

};

3.数字

function num(ctx) {
    for (let i = 0; i < 12; i++) {
        ctx.beginPath();
        ctx.moveTo(center_x, center_y)
        ctx.stroke()
        ctx.font = "16px Georgia";
        ctx.fillStyle = 'rgba(0,0,0,1)'
        ctx.fillText(clock_num[i], Math.cos(PI / 6 * (i - 2)) * log_r + center_x - 6, Math.sin(PI / 6 * (i - 2)) * log_r + center_y + 6);
    }
};

4.指针

function point(ctx, cs, size, deg) {
    ctx.save();
    ctx.beginPath();
    // ctx.moveTo(center_x, center_y)
    ctx.translate(center_x, center_y);
    ctx.rotate(3 * PI / 2 + (PI / deg) * cs);
    ctx.fillStyle = size.color;
    ctx.fillRect(0, -size.height / 2, size.width, size.height);
    // 边框设置为白色
    ctx.strokeStyle = '#ffffff'
    ctx.strokeRect(0, -size.height / 2, size.width, size.height);
    // ctx.fill();
    ctx.restore()

}

5.擦掉指针和绘制指针

function clear_point(ctx, cs, cm, ch) {
    point(ctx, cs - 1, { width: 60, height: 2, color: '#ffffff' }, 30);
    point(ctx, cm - 1, { width: 55, height: 4, color: '#ffffff' }, 30);
    point(ctx, ch - 1, { width: 50, height: 4, color: '#ffffff' }, 30);
};
function draw_point(ctx, cs, cm, ch) {
    point(ctx, cs, { width: 60, height: 2, color: '#111111' }, 30);
    point(ctx, cm, { width: 55, height: 4, color: '#111111' }, 30);
    point(ctx, ch, { width: 45, height: 4, color: '#111111' }, 6);
}

6.调用

(function() {
    var canvas = document.getElementById('myCanvas');
    var ctx = canvas.getContext('2d');
    ctx.width = 200;
    ctx.height = 200;
    disk(ctx);
    num(ctx);
    setInterval(() => {
        let ct = new Date(),
            cs = ct.getSeconds(),
            cm = ct.getMinutes(),
            ch = ct.getHours();
        clear_point(ctx, cs, cm, ch);
        draw_point(ctx, cs, cm, ch);
    }, 1000);
})();
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值