diff --git a/src/helpers/misc.ts b/src/helpers/misc.ts index ceba5113f0..5d3f60a68b 100644 --- a/src/helpers/misc.ts +++ b/src/helpers/misc.ts @@ -131,13 +131,22 @@ export function getDefaultCellHeight(style: Style | undefined, numberOfLines?: n } export function computeTextWidth(context: CanvasRenderingContext2D, text: string, style: Style) { - context.save(); - context.font = computeTextFont(style); - const textWidth = context.measureText(text).width; - context.restore(); - return textWidth; + const font = computeTextFont(style); + if (!textWidthCache[font]) { + textWidthCache[font] = {}; + } + if (textWidthCache[font][text] === undefined) { + context.save(); + context.font = font; + const textWidth = context.measureText(text).width; + context.restore(); + textWidthCache[font][text] = textWidth; + } + return textWidthCache[font][text]; } +const textWidthCache: Record> = {}; + export function computeTextFont(style: Style): string { const italic = style.italic ? "italic " : ""; const weight = style.bold ? "bold" : DEFAULT_FONT_WEIGHT;