0

Related to Calculate text width with JavaScript.

We have a situation where we have user documents with text and other objects on them placed freehand, and we need to calculate the bounds of each item before rendering the document.

I suggested that, for the text elements, we could do this by calling CanvasRenderingContext2D.measureText(), thus doing all of this relatively quickly and off screen. However, one of my co-workers emphatically stated that this would not work, because Canvas and HTML use different text rendering algorithms and could thus lead to incorrect results.

Is this correct? And if so, by how much? Is it a difference of one or two pixels (to the point where it would not affect width and height by any appreciable amount), or can certain text sequences, fonts, browsers, or OSes create hugely different results?

Some additional details:

  • Doing this calculation before document render is preferred - the document is not stored in an HTML format. The current alternative solution is to render the text once in HTML, then calculate the size from there. This displays a single HTML frame with the document's size yet unknown, which can produce unwanted visual artifacts if the text runs off the page during that frame.
  • At the time we calculate the text size, we know the font's family, size, and weight, so there are no concerns about recursive styling affecting the size.
TheHans255
  • 2,059
  • 1
  • 19
  • 36
  • Yes, I think your co-worker is correct. For one thing, canvas is a rasterized image where the browser engine is always able to relayout. Think of zooming and what not. – Brad Jul 18 '19 at 01:13
  • @Brad That affects when the text rendering algorithm is called, but not necessarily the algorithm itself. One could implement the HTML layout by calling the Canvas layout automatically every time the text changes or zooms. The HTML result is also a rasterized image at the moment it is shown to the user. – TheHans255 Sep 08 '19 at 17:51

0 Answers0