import { ref, onMounted } from "vue";
const canvasRef = ref<HTMLCanvasElement | null>(null);
const Width = 400;
const Height = 400;
type Key = {
x: number;
y: number;
w: number;
h: number;
code: string;
};
const keyLayout: Key[] = [
{
x: 5,
y: 5,
w: 10,
h: 9,
code: "ESC",
},
{
x: 16,
y: 5,
w: 9,
h: 9,
code: "F1",
},
];
const render = (ctx: CanvasRenderingContext2D) => {
ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
keyLayout.forEach(key => {
createKeyRect(ctx, key);
});
};
function createKeyRect(ctx: CanvasRenderingContext2D, params: Key) {
const { x, y, w, h, code } = params;
const canvasWidth = ctx.canvas.width;
const canvasHeight = ctx.canvas.height;
const x_ = (canvasWidth * x) / 100;
const y_ = (canvasHeight * y) / 100;
const w_ = (canvasWidth * w) / 100;
const h_ = (canvasHeight * h) / 100;
// 绘制矩形
ctx.beginPath();
ctx.rect(x_, y_, w_, h_);
ctx.fillStyle = "#ff8002";
ctx.stroke();
ctx.fill();
ctx.fillStyle = "#FFFFFF";
ctx.font = `${w_ * 0.3}px`;
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillText(code, x_ + w_ / 2, y_ + h_ / 2);
}
onMounted(() => {
if (!canvasRef.value) return;
canvasRef.value.width = Width;
canvasRef.value.height = Height;
const ctx = canvasRef.value.getContext("2d");
if (!ctx) return;
render(ctx);
});