From 67c66e1e3914e20322de4bb093351833d3a82cd4 Mon Sep 17 00:00:00 2001 From: Admin Date: Tue, 9 Jan 2024 14:34:40 +0800 Subject: [PATCH] =?UTF-8?q?fix(=E8=A7=86=E5=9B=BE):=20=E4=BF=AE=E5=A4=8D?= =?UTF-8?q?=E7=A9=BA=E6=A0=BC=E5=AF=BC=E8=87=B4Element=E5=AE=BD=E5=BA=A6?= =?UTF-8?q?=E5=B0=8F=E4=BA=8E=E6=96=87=E5=AD=97=E5=AE=BD=E5=BA=A6=E3=80=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- tiny-whiteboard/src/utils/index.js | 19 +++++++++---------- 1 file changed, 9 insertions(+), 10 deletions(-) diff --git a/tiny-whiteboard/src/utils/index.js b/tiny-whiteboard/src/utils/index.js index 43ecdfc..a1b65f9 100644 --- a/tiny-whiteboard/src/utils/index.js +++ b/tiny-whiteboard/src/utils/index.js @@ -241,17 +241,12 @@ export const splitTextLines = text => { let textCheckEl = null export const getTextActWidth = (text, style) => { if (!textCheckEl) { - textCheckEl = document.createElement('div') - textCheckEl.style.position = 'fixed' - textCheckEl.style.left = '-99999px' - document.body.appendChild(textCheckEl) + textCheckEl = createCanvas(300,200) + textCheckEl.ctx.textBaseline = "middle" } - let { fontSize, fontFamily } = style - textCheckEl.innerText = text - textCheckEl.style.fontSize = fontSize + 'px' - textCheckEl.style.fontFamily = fontFamily - let { width } = textCheckEl.getBoundingClientRect() - return width + textCheckEl.ctx.font = `${style.fontSize}px ${style.fontFamily}` + textCheckEl.ctx.fillText(text, 0, 0) + return textCheckEl.ctx.measureText(text).width } // 计算固定宽度内能放下所有文字的最大字号 @@ -278,6 +273,10 @@ export const getWrapTextActWidth = element => { if (width > maxWidth) { maxWidth = width } + if (textCheckEl) { + const {canvas, ctx} = textCheckEl + ctx.clearRect(-canvas.width / 2, -canvas.width / 2, canvas.width * 2, canvas.width * 2) + } }) return maxWidth }