7305要13*13字体

This commit is contained in:
微微一笑
2025-12-15 17:31:43 +08:00
parent 80f0ec15b3
commit 8a9a35b2bd

View File

@ -35,7 +35,9 @@
currentCanvasWidth: 0,
currentCanvasHeight: 0,
// Canvas上下文复用
ctx: null
ctx: null,
// 标记画布是否已预热(解决首次发送像素不完整问题)
canvasWarmed: false
};
},
computed: {
@ -63,10 +65,63 @@
this.ctx.fillRect(0, 0, this.currentCanvasWidth, this.currentCanvasHeight);
},
/**
* 预热画布,防止 APP 首次调用时获取到的像素数据不完整
*/
async warmupCanvas() {
if (this.canvasWarmed) {
return;
}
try {
// 先用一个最小画布绘制测试字形,触发字体和 canvas 初始化
this.currentCanvasWidth = 16;
this.currentCanvasHeight = 16;
this.clearCanvas();
this.ctx.setFillStyle(this.color);
this.ctx.setFontSize(this.fontSize);
this.ctx.font = `${this.fontSize}px "PingFangBold", "PingFang SC", Arial, sans-serif`;
this.ctx.setTextBaseline('middle');
this.ctx.fillText('测', 0, 8);
await new Promise((resolve) => {
this.ctx.draw(false, () => {
// 读取一次数据,确保 canvasGetImageData 就绪
setTimeout(() => {
uni.canvasGetImageData({
canvasId: 'reusableCanvas',
x: 0,
y: 0,
width: 16,
height: 16,
success: () => {
this.canvasWarmed = true;
resolve();
},
fail: () => {
// 即便失败也认为已尝试过,避免反复预热阻塞流程
this.canvasWarmed = true;
resolve();
}
});
}, 100);
});
});
// 额外等待,确保字体完全加载
await new Promise(resolve => setTimeout(resolve, 200));
} catch (ex) {
console.log("画布预热异常:", ex);
this.canvasWarmed = true;
}
},
/**
* 复用单个Canvas处理所有文本行
*/
async drawAndGetPixels() {
// 首次调用先做预热,避免第一次上报缺字
await this.warmupCanvas();
let binaryToHex = (binaryArray) => {
if (!Array.isArray(binaryArray) || binaryArray.length !== 8) {
throw new Error("输入必须是包含8个元素的二进制数组");
@ -92,7 +147,7 @@
let convertCharToMatrix = (imageData, item) => {
const charWidth = 13;
const charHeight = 12;
const charHeight = 13;
const pixels = [];
for (let i = 0; i < imageData.length; i += 4) {
const R = imageData[i];
@ -123,7 +178,7 @@
// 1. 动态调整Canvas尺寸
this.currentCanvasWidth = 13;
this.currentCanvasHeight = 12;
this.currentCanvasHeight = 13;
// 2. 清空Canvas绘制背景
this.clearCanvas();