无需渲染即可测量文本宽度/高度 [英] Measuring text width/height without rendering

查看:18
本文介绍了无需渲染即可测量文本宽度/高度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法在不渲染实际元素的情况下估算文本宽度?像画布 TextMetrics 之类的东西?

Is there any way to get an estimate for text width without rendering the actual elements? Something like canvas TextMetrics?

案例:我需要估计 ReactList 的元素高度.为此,我需要大致知道文本元素需要多少空间(或它们将跨越多少行).

Case: I need to estimate element heights for ReactList. To do that I'd need to know roughly how much space the text elements will need (or how many lines will they span).

例如

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

如果我知道 someText 将被渲染成一行的宽度以及该行的长度,我就可以轻松地对组件高度进行合理的估计.

If I knew how wide someText would be rendered into one line and how long the line would be, I could easily come up with a decent estimate for the components height.

请注意,这对性能非常关键,不应触及DOM

Note that this is quite performance critical and DOM should not be touched

推荐答案

请检查这个.是使用画布的解决方案

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());

演示使用

编辑

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

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

编辑

canvas 规范没有给我们测量字符串高度的方法,因此我们可以使用 parseInt(context.font).获取宽度和高度.此技巧仅适用于 px 大小.

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

这篇关于无需渲染即可测量文本宽度/高度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆