hoosierEE hoosierEE -5 years ago 228
Javascript Question

measureText() tab character

I expected a

character would be wider than a
character, but in HTML5 canvas, they are the same. Plus a few others, which aren't as much of a concern:

var c=document.getElementById('mycanvas').getContext('2d');
c.font='24px Sans-Serif';
c.measureText('\t').width; // 7
c.measureText('\r').width; // 7
c.measureText('\n').width; // 7
c.measureText(' ').width; // 7
c.measureText('\b').width; // 0
c.measureText('a').width; // 13

I'm rendering text in
, and would like to make
have an unsurprising width relative to a
. What value (multiple?) should I use?

Answer Source

You can be assured that context.measureText('\t') will always return the width of a space character in the current font.

Here's why...

.measureText measures text using the inline box.

WhatWG.org specifies that measureText.width return the inline-box value:


The measureText() method takes one argument, text. When the method is invoked, the user agent must run the text preparation algorithm, passing it text and the object implementing the CanvasText interface, and then using the returned inline box must create a new TextMetrics object with its attributes set as described [...as follows]:

width attribute: The width of that inline box, in CSS pixels. (The text's advance width.)

Inline box collapses the tab character into a space character.

W3.org specifies that a tab character is collapsed into a space:


For each inline element (including anonymous inline elements), the following steps are performed, treating bidi formatting characters as if they were not there...

...every tab (U+0009) is converted to a space (U+0020)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download