javascript 无需渲染即可测量文本宽度/高度
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31305071/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Measuring text width/height without rendering
提问by Seppo420
Is there any way to get an estimate for text width without rendering the actual elements? Something like canvas TextMetrics?
有没有办法在不渲染实际元素的情况下估算文本宽度?像画布 TextMetrics 之类的东西?
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).
案例:我需要估计 ReactList 的元素高度。为此,我需要大致知道文本元素需要多少空间(或它们将跨越多少行)。
eg.
例如。
render(){
return <div><SomeComponentWithKnownDims/><p>{this.props.someText}</p></div>;
}
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.
如果我知道 someText 将被渲染成一行的宽度以及该行的长度,我就可以很容易地对组件高度进行适当的估计。
EDIT: Note that this is quite performance critical and DOM should not be touched
编辑:请注意,这对性能非常关键,不应触及 DOM
回答by vasilenicusor
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());
EDIT
编辑
The solution using canvas is not the best, each browser deal different canvas size.
使用画布的解决方案并不是最好的,每个浏览器处理不同的画布大小。
Hereis 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.
画布规范没有给我们测量字符串高度的方法,因此我们可以使用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']);