From 8a9a35b2bdfbe631a8e8470f5c4350c6b478c191 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=BE=AE=E5=BE=AE=E4=B8=80=E7=AC=91?= <709648985@qq.com> Date: Mon, 15 Dec 2025 17:31:43 +0800 Subject: [PATCH] =?UTF-8?q?7305=E8=A6=8113*13=E5=AD=97=E4=BD=93?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../TextToHex/textToDotMatrixFor7305.vue | 61 ++++++++++++++++++- 1 file changed, 58 insertions(+), 3 deletions(-) diff --git a/components/TextToHex/textToDotMatrixFor7305.vue b/components/TextToHex/textToDotMatrixFor7305.vue index 7160bf5..48fbea8 100644 --- a/components/TextToHex/textToDotMatrixFor7305.vue +++ b/components/TextToHex/textToDotMatrixFor7305.vue @@ -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();