In HTML 5 , you can just use the Canvas.measureText method (further explanation here ).(在HTML 5中 ,您可以仅使用Canvas.measureText方法 ( 此处有更多说明)。)
Try this fiddle :(试试这个小提琴 :)
/**
* Uses canvas.measureText to compute and return the width of the given text of given font in pixels.
*
* @param {String} text The text to be rendered.
* @param {String} font The css font descriptor that text is to be rendered with (e.g. "bold 14px verdana").
*
* @see https://stackoverflow.com/questions/118241/calculate-text-width-with-javascript/21015393#21015393
*/
function getTextWidth(text, font) {
// re-use canvas object for better performance
var canvas = getTextWidth.canvas || (getTextWidth.canvas = document.createElement("canvas"));
var context = canvas.getContext("2d");
context.font = font;
var metrics = context.measureText(text);
return metrics.width;
}
console.log(getTextWidth("hello there!", "bold 12pt arial")); // close to 86
This fiddle compares this Canvas method to a variation of Bob Monteverde's DOM-based method , so you can analyze and compare accuracy of the results.(这个小提琴将这种Canvas方法与Bob Monteverde基于DOM的方法的变体进行了比较,因此您可以分析和比较结果的准确性。)
There are several advantages to this approach, including:(这种方法有几个优点,包括:)
- More concise and safer than the other (DOM-based) methods because it does not change global state, such as your DOM.(比其他(基于DOM)方法更简洁,更安全,因为它不会更改全局状态(例如DOM)。)
- Further customization is possible by modifying more canvas text properties , such as
textAlign
and textBaseline
.(通过修改更多的画布文本属性 (例如textAlign
和textBaseline
,可以进行进一步的自定义。)
NOTE: When you add the text to your DOM, remember to also take account of padding, margin and border .(注意:将文本添加到DOM时,请记住还要考虑padding,margin和border 。)
NOTE 2: On some browsers, this method yields sub-pixel accuracy (result is a floating point number), on others it does not (result is only an int).(注意2:在某些浏览器上,此方法产生子像素精度(结果是浮点数),在其他浏览器上则没有(结果只是整数)。)
You might want to run Math.floor
(or Math.ceil
) on the result, to avoid inconsistencies.(您可能要对结果运行Math.floor
(或Math.ceil
),以避免不一致。) Since the DOM-based method is never sub-pixel accurate, this method has even higher precision than the other methods here.(由于基于DOM的方法永远不会精确到子像素,因此此方法比此处的其他方法具有更高的精度。)
According to this jsperf (thanks to the contributors in comments), the Canvas method and the DOM-based method are about equally fast, if caching is added to the DOM-based method and you are not using Firefox.(根据这个jsperf的介绍 (感谢评论中的贡献者),如果将缓存添加到基于DOM的方法中并且您未使用Firefox,则Canvas方法和基于DOM的方法的速度差不多 。)
In Firefox, for some reason, this Canvas method is much much faster than the DOM-based method (as of September 2014).(在Firefox中,由于某种原因,这种Canvas方法比基于DOM的方法 (截至2014年9月)要快得多。) 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…