To accommodate 'letter kerning pairs' and similar aspects, I have crafted the following solution. It has been designed to consider these factors, and initial testing indicates it functions as intended. For feedback or insights, please refer to my related query on the matter (Adding Letter Spacing in HTML Canvas)
The approach involves utilizing measureText() to ascertain the total width of the string, then removing the first character to measure the remaining string's width. This technique accounts for kerning pairs and related elements. Further details can be found in the provided link.
Below is the specified HTML setup:
<canvas id="Test1" width="800px" height="200px"><p>Your browser does not support canvas.</p></canvas>
Here is the code snippet:
this.fillTextWithSpacing = function(context, text, x, y, spacing)
{
//Begin at coordinates (X, Y).
//Calculate wAll, the total string width using measureText()
wAll = context.measureText(text).width;
do
{
//Remove the first character from the string
char = text.substr(0, 1);
text = text.substr(1);
//Display the initial character at (X, Y) using fillText()
context.fillText(char, x, y);
//Determine wShorter, the width of the shortened string using measureText().
if (text == "")
wShorter = 0;
else
wShorter = context.measureText(text).width;
//Calculate the kerned width of the character by subtracting the shorter string width from the total string width, wChar = wAll - wShorter
wChar = wAll - wShorter;
//Advance X by wChar + spacing
x += wChar + spacing;
//Update wAll to wShorter
wAll = wShorter;
//Repeat from step 3
} while (text != "");
}
Demonstration code for testing purposes:
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);
It would be ideal to conduct thorough assessment by feeding various random strings and conducting pixel-by-pixel evaluations. Additionally, I am uncertain about the default kerning performance of Verdana, although I've heard it surpasses Arial - recommendations for alternative fonts to test are welcomed.
Thus far, the results appear promising, even flawless.
However, I remain open to any critiques or suggestions that may help enhance the process.
In the meantime, I am sharing this information for the benefit of others seeking a solution in this area.