TrueType Fonts in JavaScript with Font-Face

The JavaScript code below, when run, presents an interface that allows the user to specify a font file in TTF format and some text to render in that font. Then, when the button is clicked, the specified text is rendered using the specified font.

To see the code in action, copy it into an .html file and open that file in a web browser that runs JavaScript. You’ll also need to locate a .ttf file. On Windows machines, a good place to look is in the “C:\Windows\fonts” folder, which is where I found the “impact.ttf” file that I used in my testing.

FontFromFile


<html>
<body>

<!-- ui -->

<div>
	<label>Font File:</label>
	<input id="inputFontFile" type="file"></input>
</div>
<div>
	<label>Text to Draw:</label>
	<input id="inputTextToDraw" value="The quick fox jumped over the lazy dogs."></input>
</div>
<div><button id="buttonDrawTextWithFont" onclick="buttonDrawTextWithFont_Clicked();">Draw Text with Font</button></div>
<div style="border:1px solid">
	<canvas id="canvasOutput" width="300" height="40"></canvas>
<div>

<script type="text/javascript">

// ui event handlers

function buttonDrawTextWithFont_Clicked()
{
	var inputFontFile = document.getElementById("inputFontFile");

	var fontFile = inputFontFile.files[0];

	if (fontFile == null)
	{
		alert("No font file specified!");
	}
	else
	{
		var fontFileReader = new FileReader();
		fontFileReader.onload = 
			buttonDrawTextWithFont_Clicked_FontFileLoaded;
		fontFileReader.readAsDataURL(fontFile);
	}	
}

function buttonDrawTextWithFont_Clicked_FontFileLoaded(fileLoadedEvent)
{
	var fontFileReader = fileLoadedEvent.target;
	var fontFileAsDataURL = fontFileReader.result;

	var inputFontFile = document.getElementById("inputFontFile");
	var fontName = inputFontFile.files[0].name.split(".")[0];

	var fontAsStyleElement = document.createElement("style");
	fontAsStyleElement.innerHTML = 
		"@font-face { "
		+ "font-family: '" + fontName + "';"
		+ "src: url('" + fontFileAsDataURL + "');"; 
		+ "}"

	document.head.appendChild(fontAsStyleElement);	

	var inputTextToDraw = document.getElementById("inputTextToDraw");
	var textToDraw = inputTextToDraw.value;

	var canvasOutput = document.getElementById("canvasOutput");
	var graphics = canvasOutput.getContext("2d");

	graphics.font = "16px " + fontName;
	graphics.fillStyle = "Black";
	graphics.fillText(textToDraw, 0, canvasOutput.height / 2);
}

</script>

</body>
</html>

This entry was posted in Uncategorized and tagged , , , , . Bookmark the permalink.

Leave a comment