为了允许“字母字距调整对”等,我写了以下内容。它应该考虑到这一点,粗略的测试表明确实如此。如果您对此有任何意见,那么我会指出我关于该主题的问题(在 HTML 画布中添加字母间距)
基本上它使用 measureText() 来获取整个字符串的宽度,然后删除字符串的第一个字符并测量剩余字符串的宽度,并使用差异来计算正确的定位 - 因此考虑到字距对和类似。有关更多伪代码,请参见给定的链接。
这是HTML:
<canvas id="Test1" width="800px" height="200px"><p>Your browser does not support canvas.</p></canvas>
这是代码:
this.fillTextWithSpacing = function(context, text, x, y, spacing)
{
//Start at position (X, Y).
//Measure wAll, the width of the entire string using measureText()
wAll = context.measureText(text).width;
do
{
//Remove the first character from the string
char = text.substr(0, 1);
text = text.substr(1);
//Print the first character at position (X, Y) using fillText()
context.fillText(char, x, y);
//Measure wShorter, the width of the resulting shorter string using measureText().
if (text == "")
wShorter = 0;
else
wShorter = context.measureText(text).width;
//Subtract the width of the shorter string from the width of the entire string, giving the kerned width of the character, wChar = wAll - wShorter
wChar = wAll - wShorter;
//Increment X by wChar + spacing
x += wChar + spacing;
//wAll = wShorter
wAll = wShorter;
//Repeat from step 3
} while (text != "");
}
演示/眼球测试代码:
element1 = document.getElementById("Test1");
textContext1 = element1.getContext('2d');
textContext1.font = "72px Verdana, sans-serif";
textContext1.textAlign = "left";
textContext1.textBaseline = "top";
textContext1.fillStyle = "#000000";
text = "Welcome to go WAVE";
this.fillTextWithSpacing(textContext1, text, 0, 0, 0);
textContext1.fillText(text, 0, 100);
理想情况下,我会向它抛出多个随机字符串并进行逐像素比较。我也不确定 Verdana 的默认字距调整有多好,尽管我知道它比 Arial 更好 - 对其他字体的建议值得尝试接受。
所以......到目前为止它看起来不错。事实上,它看起来很完美。仍然希望有人会指出过程中的任何缺陷。
与此同时,我会把它放在这里,让其他人看看他们是否正在寻找解决方案。