1
0
forked from dyf/APP

merge upstream

This commit is contained in:
2025-11-24 08:20:45 +08:00
2 changed files with 142 additions and 82 deletions

View File

@ -34,7 +34,9 @@
currentCanvasWidth: 0,
currentCanvasHeight: 0,
// Canvas上下文复用
ctx: null
ctx: null,
// 标记是否已经预热过画布
canvasWarmed: false
};
},
computed: {
@ -62,10 +64,67 @@
this.ctx.fillRect(0, 0, this.currentCanvasWidth, this.currentCanvasHeight);
},
/**
* 预热画布确保画布和字体完全准备好解决APP重新打开后第一次获取数据不完整的问题
*/
async warmupCanvas() {
if (this.canvasWarmed) {
return;
}
try {
// 设置画布尺寸
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 API已准备好
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() {
// 第一次调用时先预热画布解决APP重新打开后第一次获取数据不完整的问题
await this.warmupCanvas();
let convertCharToMatrix=function(imageData) {
// console.log("imgData=",imageData)
@ -119,7 +178,7 @@
// 3. 设置文字样式
ctx.setFillStyle(this.color);
ctx.setTextBaseline('middle');
ctx.setTextBaseline('middle');
// ctx.setTextAlign('center')
ctx.setFontSize(this.fontSize);
ctx.font = `${this.fontSize}px "PingFangBold", "PingFang SC", Arial, sans-serif`;