[Vuejs]-Trying to calculate the width of a text in my Nuxt App

0👍

I believe the problem might be that the measured width of the spans you’re creating isn’t accurate until an asynchronous layout task is performed.

I’ve written my own utility function for measuring text width by creating a canvas to avoid this issue. It can be found in @tubular/util. This is the code for the function:

export function getTextWidth(items: string | string[], font: string | HTMLElement, fallbackFont?: string): number {
  const canvas = ((getTextWidth as any).canvas as HTMLCanvasElement ||
                  ((getTextWidth as any).canvas = document.createElement('canvas') as HTMLCanvasElement));
  const context = canvas.getContext('2d')!;
  let maxWidth = 0;
  let elementFont;

  if (typeof font === 'string')
    elementFont = font;
  else if (typeof font === 'object')
    elementFont = getFont(font);

  if (elementFont)
    context.font = elementFont;
  else if (fallbackFont)
    context.font = fallbackFont;
  else
    context.font = 'normal 12px sans-serif';

  if (!Array.isArray(items))
    items = [items];

  for (const item of items) {
    const width = context.measureText(item).width;
    maxWidth = max(maxWidth, width);
  }

  return maxWidth;
}

Leave a comment