In my simple pixel art project Legend of the Moon Stones I wanted, of course, pixel-perfect control over the displayed text, and I didn't want to mess with missing fonts, etc. So instead of using standard canvas text functions I decided to import my own font as an image, and take care of all the typing functions.
After all, this project is also a practice in Javascript, right? First thing, I created two font sets:
A bigger one, using the same fonts of the game title, for short sentences:
and a smaller, black one for the other text:
The smaller one is also fixed-space (every character has the same width and height), and this makes typing functions a little easier.
Then, in my javascript files, I created some arrays to store the values and positions of each character inside the image:
function setupText() {
fontImage = new Image();
fontImage.src = "img/font.png";
var line1 = [ "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z" ];
var line2 = [ "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z" ];
var line3 = [ "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", ",", ".", ";", ":", "-", "!", '"', "£", "$", "%", "&", "/", "(", ")", "=", "?" ];
var line4 = [ "^", "+", "*", "#", "°", "è", "é", "à", "ò", "ù", "ì", "'", "_", " " ];
for (var i = 0; i < 26; i++) {
setFontCoord(line1[i], i * 8, 0);
setFontCoord(line2[i], i * 8, 10);
setFontCoord(line3[i], i * 8, 20);
}
for (var i = 0; i < line4.length; i++) {
setFontCoord(line4[i], i * 8, 30);
}
function setFontCoord(ch, x, y) {
fontx[ch] = x;
fonty[ch] = y;
}
now that I have the x and y coordinates of every character in the font set, I can use the drawImage() function of HTML canvas, that allows you to draw just a part of a bigger image, to display each character of a text:
function write(text, x, y) {
var dx = 0;
for (var i = 0; i < text.length; i++) {
ctx.drawImage(fontImage, fontx[text[i]], fonty[text[i]], fontDimX, fontDimY, x + dx, y, fontDimX, fontDimY);
dx += fontDimX + whiteSpace;
}
}
Here's the result, with both big and small fonts:
Then I used a timing effect to replicate the old-fashioned effect of the "self-writing" text, as in the following GIF:
(click on the image for the animation)
Now that I have working text, I can use it to show the player's score and many nice things. See you on the next part, thanks for reading!