Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
169
rated 0 times [  171] [ 2]  / answers: 1 / hits: 34400  / 9 Years ago, wed, july 8, 2015, 12:00:00

Is there any way to get an estimate for text width without rendering the actual elements? Something like canvas 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).



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.



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


More From » html

 Answers
14

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

[#65875] Tuesday, July 7, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
tomas

Total Points: 165
Total Questions: 111
Total Answers: 103

Location: Maldives
Member since Tue, Dec 21, 2021
2 Years ago
tomas questions
Thu, Jan 27, 22, 00:00, 2 Years ago
Mon, May 10, 21, 00:00, 3 Years ago
Tue, Jan 5, 21, 00:00, 3 Years ago
;