javascript - measureText() 制表符

标签 javascript html5-canvas

我预计 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/

相关文章:

html - 是否有任何理由在 2D 游戏/应用程序中使用 WebGL 而不是 2D Canvas?

javascript - 如何修复 TypeError 不是一个函数(用 Jest 测试 promises)

javascript - 由复选框生成的进度条显示在不同页面中

javascript - 如何向 Canvas 元素添加蒙版和背景

javascript - FabricJS V.2 删除多个对象

javascript - 在 Javascript 中以编程方式将 SVG 转换为图像

javascript - 如何结束 'pg-promise'应用程序

javascript - 如何将此递归函数转换为迭代函数?

javascript - 无法使用 ng-repeat 打印对象的值

javascript - Canvas 外的线条