我预计 TAB
字符会比 SPACE
字符宽,但在 HTML5 Canvas 中,它们是相同的。还有其他一些问题,但并不是那么令人担忧:
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
我正在 canvas
中渲染文本,并且希望使 TAB
相对于 SPACE
具有令人惊讶的宽度。我应该使用什么值(多个?)?
最佳答案
您可以放心,context.measureText('\t')
将始终返回当前字体中空格字符的宽度。
这就是为什么......
.measureText
使用内联框测量文本。
WhatWG.org 指定 measureText.width
返回内联框值:
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.)
行内框将制表符折叠为空格字符。
W3.org 指定制表符折叠成空格:
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)
关于javascript - measureText() 制表符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37848455/