hoosierEE hoosierEE - 5 months ago 20
Javascript Question

measureText() tab character

I expected a

TAB
character would be wider than a
SPACE
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
canvas
, and would like to make
TAB
have an unsurprising width relative to a
SPACE
. What value (multiple?) should I use?

Answer

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:

https://html.spec.whatwg.org/multipage/scripting.html#dom-context-2d-measuretext

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:

http://www.w3.org/TR/CSS2/text.html#white-space-model

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)