Skip to content

Commit

Permalink
fix: fix early create canvas context cause build error in server side (
Browse files Browse the repository at this point in the history
  • Loading branch information
kagawagao committed Dec 3, 2020
1 parent 1bf0804 commit 5cdbda3
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 2 deletions.
12 changes: 12 additions & 0 deletions src/utils/context.ts
@@ -0,0 +1,12 @@
let ctx: CanvasRenderingContext2D;

/**
* 获取 canvas context
*/
export function getCanvasContext() {
if (!ctx) {
ctx = document.createElement('canvas').getContext('2d');
}

return ctx;
}
4 changes: 2 additions & 2 deletions src/utils/measure-text.ts
@@ -1,6 +1,5 @@
import { isString, memoize, values } from '@antv/util';

const ctx = document.createElement('canvas').getContext('2d');
import { getCanvasContext } from './context';

/**
* 计算文本在画布中的宽度
Expand All @@ -10,6 +9,7 @@ const ctx = document.createElement('canvas').getContext('2d');
export const measureTextWidth = memoize(
(text: string, font: any = {}): number => {
const { fontSize, fontFamily = 'sans-serif', fontWeight, fontStyle, fontVariant } = font;
const ctx = getCanvasContext();
// @see https://developer.mozilla.org/zh-CN/docs/Web/CSS/font
ctx.font = [fontStyle, fontWeight, fontVariant, `${fontSize}px`, fontFamily].join(' ');
const metrics = ctx.measureText(isString(text) ? text : '');
Expand Down

0 comments on commit 5cdbda3

Please sign in to comment.