From b9161853527356b36ae1af906a47ef237416671d Mon Sep 17 00:00:00 2001 From: liu Date: Thu, 25 May 2023 14:32:26 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E8=AE=A1=E7=AE=97=E6=96=87=E5=AD=97?= =?UTF-8?q?=E5=AE=BD=E5=BA=A6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ✅ Closes: #15 --- src/index.ts | 1 + src/lib/computedTextWidth.ts | 15 +++++++++++++++ 2 files changed, 16 insertions(+) create mode 100644 src/lib/computedTextWidth.ts diff --git a/src/index.ts b/src/index.ts index 71c88a8..a771103 100644 --- a/src/index.ts +++ b/src/index.ts @@ -13,3 +13,4 @@ export * from "./lib/CoordinateUtils"; export * from "./lib/ajax"; export * from "./lib/browser"; export * from "./lib/getJson"; +export * from "./lib/computedTextWidth"; diff --git a/src/lib/computedTextWidth.ts b/src/lib/computedTextWidth.ts new file mode 100644 index 0000000..e3fab2d --- /dev/null +++ b/src/lib/computedTextWidth.ts @@ -0,0 +1,15 @@ +let canvas: HTMLCanvasElement; + +/** + * 计算文本宽度 + * @param {string} text - 文本 + * @param {string} font - 字体 + * @returns {number} - 宽度 + */ +export function computedTextWidth(text: string, font: string) { + canvas = canvas ?? document.createElement("canvas"); + const context = canvas.getContext("2d"); + context!.font = font; + const metrics = context!.measureText(text); + return metrics.width; +}