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.



<!-- ui -->

	<label>Font File:</label>
	<input id="inputFontFile" type="file"></input>
	<label>Text to Draw:</label>
	<input id="inputTextToDraw" value="The quick fox jumped over the lazy dogs."></input>
<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>

<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!");
		var fontFileReader = new FileReader();
		fontFileReader.onload = 

function buttonDrawTextWithFont_Clicked_FontFileLoaded(fileLoadedEvent)
	var fontFileReader =;
	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 + "');"; 
		+ "}"


	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);



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

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s