简体   繁体   中英

Measuring length of string in pixel in javascript

如果我知道font-size和font-family,如何在javascript中找到字符串的长度(以像素为单位)?

The simplest solution is to create an in memory canvas (ie one that isn't added to the DOM) and then use the measureText function :

var canvas = document.createElement('canvas');
var ctx = canvas.getContext("2d");
ctx.font = "11px Arial";        
var width = ctx.measureText(str).width;

you can put your string into paragraph and use the jquery width function to get the width in pixel width

    function showWidth(ele, w) {
$("div").text("The width for the " + ele +
" is " + w + "px.");
}
$("#getp").click(function () {
showWidth("paragraph", $("p").width());
});

check jsfiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM