4
Emscripten: FreeType Demo
6
<script type="text/javascript">
10
<script src="freetype.cc.js"></script>
11
<script type="text/javascript">
12
// print function which the runtime will call
13
function print(text) {
14
//document.getElementById('output').innerHTML += text + '<br>';
17
// Override the _show_image in freetype.js.
18
__Z10show_imagev = function() {
19
var canvas = document.getElementById('canvas');
20
var ctx = canvas.getContext('2d');
21
var image = ctx.getImageData(0, 0, canvas.width, canvas.height);
23
var ptr = IHEAP[_image];
24
for (var y = 0; y < canvas.height; y++) {
25
for (var x = 0; x < canvas.width; x++) {
26
var value = IHEAP[ptr + y*canvas.width + x];
27
var base = (y*canvas.width + x)*4;
28
image.data[base + 0] = value;
29
image.data[base + 1] = value;
30
image.data[base + 2] = value;
31
image.data[base + 3] = 255;
34
ctx.putImageData(image, 0, 0);
37
function render(angle, text) {
38
var canvas = document.getElementById('canvas');
42
run(['font.ttf', text, canvas.width.toString(), canvas.height.toString(), angle.toString()]); // will call _show_image, above
46
<body onload="render(10, 'Hello world!')">
47
<h1>TrueType Fonts in JavaScript</h1>
48
<p>This is a demo of <a href="http://www.freetype.org/">FreeType</a>, an open source font engine written in C++,
49
compiled to JavaScript using <a href="http://emscripten.org">Emscripten</a>. A <a href="http://en.wikipedia.org/wiki/TrueType">TrueType</a> font
50
(<a href="https://fedorahosted.org/liberation-fonts/">Liberation Sans Bold</a>) is loaded in FreeType and used to render text, all entirely in JavaScript.
52
<p>(Note: The demo is a proof of concept and <b>not</b> optimized for speed. For example, the font file is
53
loaded and parsed every time text is rendered. Also, the code is a debug build with runtime checks for
55
<p>Why was this demo done? Just to show it's possible, and definitely not to suggest people should do things this way.
56
If you want nice fonts on the web, use <a href="http://en.wikipedia.org/wiki/Web_Open_Font_Format">WOFF</a>.</p>
58
<canvas id='canvas' width=1 height=1></canvas>
60
<form onsubmit="render(parseInt(angle.value), texty.value); return false">
61
Text: <input type="text" name="texty" value="Hello world!"><br>
62
Angle (in degrees): <input type="text" name="angle" value="10"><br>
63
<input type="submit" value="Go!">
65
<div id="output" style="font-family: Courier New,Courier,monospace;"></div>