Method 1: Create a new DOM Element and measure its width.
A new “span” element is created with the createElement() method. Then added it to the body of the element using the appendChild() method. The style property of this element is used to set properties like the font, font-size, height, width, whiteSpace, and position. The font is set to the string with the font needed. The font-size is a string with a value in pixels. The height and width properties are set to ‘auto’. The position property is set to ‘absolute’ and the whiteSpace property is set to ‘no-wrap’. The text to be measured is specified using the innerHTML property. The clientWidth property is used to get the width of its element. This value will represent the width of text in pixels. The element is then removed using the removeChild() method.
Method 2: Using the canvas measureText() method.
A new “canvas” element is created with the createElement() method. The 2d context required to draw graphics is accessed using the getContext() method and passing the value “2d” as the parameter. This context will be used to manipulate the text in the canvas. The font is specified using the font property. The font string uses the same syntax as a CSS font specifier. The dimensions of the text are calculated using the measureText() method. The text to be measured is passed to this method. It returns a TextMetrics object that contains information about the measured text. The width property of this TextMetrics object is used to get the width of the text. The width may be a floating-point value, hence the Math.ceil() function is used to find the ceiling of the floating-point and return an integer. This value is the width of the measured text in pixels.
Please Login to comment...