用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);
})();