gpt4 book ai didi

javascript - measureText() 制表符

转载 作者:行者123 更新时间:2023-11-29 16:49:11 31 4
gpt4 key购买 nike

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

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com