Measuring text width/height without rendering

冷暖自知 提交于 2019-11-27 21:15:10

Please check this. is a solution using canvas

function get_tex_width(txt, font) {
        this.element = document.createElement('canvas');
        this.context = this.element.getContext("2d");
        this.context.font = font;
        return this.context.measureText(txt).width;
    }
    alert('Calculated width ' + get_tex_width("Hello World", "30px Arial"));
    alert("Span text width "+$("span").width());

Demo using

EDIT

The solution using canvas is not the best, each browser deal different canvas size.

Here is a nice solution to get size of text using a temporary element. Demo

EDIT

The canvas spec doesn't give us a method for measuring the height of a string, so for this we can use parseInt(context.font). TO get width and height. This trick work only with px size.

function get_tex_size(txt, font) {
    this.element = document.createElement('canvas');
    this.context = this.element.getContext("2d");
    this.context.font = font;
    var tsize = {'width':this.context.measureText(txt).width, 'height':parseInt(this.context.font)};
    return tsize;
}
var tsize = get_tex_size("Hello World", "30px Arial");

alert('Calculated width ' + tsize['width'] + '; Calculated height ' + tsize['height']);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!