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.