Home >Web Front-end >JS Tutorial >How Can I Calculate Text Width in JavaScript Using the Canvas Method?
Calculating the width of a string using JavaScript is not immediately straightforward, especially when using a non-monospace typeface. Here, we explore a solution using the Canvas.measureText method in HTML 5.
To use Canvas.measureText, we create a canvas context and assign it the desired font style. Then, we use the measureText method to measure the width of the specified text.
function getTextWidth(text, font) { const canvas = getTextWidth.canvas || (getTextWidth.canvas = document.createElement("canvas")); const context = canvas.getContext("2d"); context.font = font; const metrics = context.measureText(text); return metrics.width; }
For example, to calculate the width of "hello there!" in "bold 12pt arial" font, we can do:
console.log(getTextWidth("hello there!", "bold 12pt arial")); // close to 86
If we want to use the font-size of a specific element, we can use the getCanvasFont utility function:
const fontSize = getTextWidth(text, getCanvasFont(myEl));
Compared to DOM-based methods, the Canvas method has several advantages:
A jsperf benchmark shows that the Canvas method and a caching DOM-based method have similar performance, except in Firefox where the Canvas method is notably faster.
The above is the detailed content of How Can I Calculate Text Width in JavaScript Using the Canvas Method?. For more information, please follow other related articles on the PHP Chinese website!