dcsimg
www.webdeveloper.com
Results 1 to 3 of 3

Thread: Getting Width of text before writing to the document

  1. #1
    Join Date
    Feb 2011
    Posts
    3

    Getting Width of text before writing to the document

    I have the following code which I use to get the width of a piece of text.
    Code:
    function getTextWidth(text, font)
    {
    	var canvas = document.createElement('span');
    	canvas.style.fontSize = font;
    	canvas.innerHTML = text;
    	var width = canvas.innerWidth;
    	return width;
    }
    canvas.innerWidth is undefined and I am not sure why. Is there something I have missed or is there some other way where I can get the width of a text before I even write it to the document with Javascript?

    Thanks

  2. #2
    Join Date
    Sep 2015
    Posts
    95
    Try:

    Code:
    function getTextWidth(text, font)
    {
    
    	var canvas = document.createElement('span');
    document.body.appendChild(canvas);  //you forgot to append inside body
    	canvas.style.fontSize = font;
    	canvas.innerHTML = text;
    	var width = canvas.offsetWidth; //use offsetWidth instead
    	return width;
    }
    https://jsfiddle.net/c0ca8ky5/

  3. #3
    Join Date
    Feb 2011
    Posts
    3
    offsetWidth did it! Thanks!

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles