I don't know shite about:

Calculate text width with canvas

Get the exact width of a text element with HTML Canvas

Today I needed to calculate the length of a text element to embelish it with custom svg text decoration.

I found this useful function that tells me the text element width in pixel based on the input string, font, fontSize, fontWeight without rendering it onto the DOM. The function renders the text element onto a canvas and uses the canvas .measureText() method to retrieve the width.

function getTextWidth(text, font, fontSize, fontWeight) {
  const canvas = document.createElement("canvas");
  const context = canvas.getContext("2d");
  context.font = `${fontWeight} ${fontSize} ${font}`;
  const metrics = context.measureText(text);
  return metrics.width;
}

In this contrived example I fetched images from unsplash with the exact measurement retrieved from the getTextWidth() function.