There are DOM methods that are used to calculate the text width; however in this tutorial, you will find the best method to do the task accordingly.
italic 19pt verdana).
The measureText() Method
The measureText() method returns an object which represents the width of the given text in terms of pixels. It can be used to detect the text width before writing it on canvas.
This approach has some advantages:
- It is more concise and safer than the other DOM-based methods as it does not change the global state.
- Further customization is possible by modifying more canvas text properties, such as textAlign and textBaseline.
This method provides sub-pixel accuracy, i.e. the result is a floating-point number on some browsers; on others it does not. In such cases, you should run Math.floor (or Math.ceil) on the result to avoid inconsistencies. The Canvas.measureText() method is the fastest compared to the other methods.