测量文本宽度/高度而不渲染

Measuring text width/height without rendering

本文关键字:高度 文本 测量      更新时间:2023-09-26

是否有任何方法可以在不呈现实际元素的情况下获得文本宽度的估计?比如canvas TextMetrics?

案例:我需要估计ReactList的元素高度。要做到这一点,我需要大致知道文本元素将需要多少空间(或者它们将跨越多少行)。

render(){
    return <div><SomeComponentWithKnownDims/><p>{this.props.someText}</p></div>;
}

如果我知道someText渲染成一行的宽度和长度,我就可以很容易地估计出组件的高度。

编辑:注意,这是相当关键的性能和DOM不应该被触摸

请检查。是使用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());

使用

演示

编辑

使用画布的解决方案不是最好的,每个浏览器处理不同的画布大小。

下面是使用临时元素获取文本大小的一个很好的解决方案。演示

编辑

画布规格没有给我们测量字符串高度的方法,所以我们可以使用parseInt(context.font)。得到宽度和高度。这个技巧只适用于px大小。

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']);