Skip to content

Commit

Permalink
feat: 计算文字宽度
Browse files Browse the repository at this point in the history
Closes: #15
  • Loading branch information
liu committed May 25, 2023
1 parent 6898f86 commit b916185
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,3 +13,4 @@ export * from "./lib/CoordinateUtils";
export * from "./lib/ajax";
export * from "./lib/browser";
export * from "./lib/getJson";
export * from "./lib/computedTextWidth";
15 changes: 15 additions & 0 deletions src/lib/computedTextWidth.ts
Original file line number Diff line number Diff line change
@@ -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;
}

0 comments on commit b916185

Please sign in to comment.