Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: provide a mock function to measure text width #311

Merged
merged 1 commit into from
Nov 10, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading