好吧,我已经根据上面的伪代码编写了代码,并通过屏幕截图和目视差异进行了一些比较(缩放,使用例如剪辑框中的直线来比较每个字符的 X 位置和宽度)。对我来说看起来完全一样,间距设置为 0。
这是 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 更好 - 关于其他字体的建议,请尝试感激地接受。
所以...到目前为止看起来还不错。事实上它看起来很完美。
还是希望有人能指出这个过程中的任何缺陷。
与此同时,我会将其放在这里供其他人看看他们是否正在寻找解决方案。