Skip to content

Commit

Permalink
fix: provide a mock function to measure text width
Browse files Browse the repository at this point in the history
  • Loading branch information
xiaoiver committed Nov 10, 2023
1 parent 74abd22 commit f0b4c13
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 1 deletion.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@antv/component",
"version": "1.0.0-beta.1",
"version": "1.0.0-beta.2",
"description": "Visualization components for AntV, based on G.",
"license": "MIT",
"main": "lib/index.js",
Expand Down
10 changes: 10 additions & 0 deletions src/util/text.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,11 @@ import { isString, memoize } from '@antv/util';
import type { DisplayObject, Text } from '../shapes';

let ctx: CanvasRenderingContext2D;
let mockMeasureTextWidth: ((text: string, fontSize: number) => number) | undefined;

export function setMockMeasureTextWidth(mock: (text: string, fontSize: number) => number) {
mockMeasureTextWidth = mock;
}

/**
* 计算文本在画布中的宽度
Expand All @@ -10,6 +15,11 @@ export const measureTextWidth = memoize(
(text: string | Text, font?: any): number => {
const content = isString(text) ? text : text.style.text.toString();
const { fontSize, fontFamily, fontWeight, fontStyle, fontVariant } = font || getFont(text as Text);

if (mockMeasureTextWidth) {
return mockMeasureTextWidth(content, fontSize);
}

if (!ctx) {
ctx = document.createElement('canvas').getContext('2d') as CanvasRenderingContext2D;
}
Expand Down

0 comments on commit f0b4c13

Please sign in to comment.