javascript - Measuring text width/height without rendering -


is there way estimate text width without rendering actual elements? canvas textmetrics?

case: need estimate element heights reactlist. i'd need know how space text elements need (or how many lines span).

eg.

render(){     return <div><somecomponentwithknowndims/><p>{this.props.sometext}</p></div>; } 

if knew how wide sometext rendered 1 line , how long line be, come decent estimate components height.

edit: note quite performance critical , dom should not touched

please check this. 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 not best, each browser deal different canvas size.

here nice solution size of text using temporary element. demo

edit

the canvas spec doesn't give method measuring height of string, can use parseint(context.font). width , height. trick work 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']); 

Comments

Popular posts from this blog

python - No exponential form of the z-axis in matplotlib-3D-plots -

php - Best Light server (Linux + Web server + Database) for Raspberry Pi -

c# - "Newtonsoft.Json.JsonSerializationException unable to find constructor to use for types" error when deserializing class -