KQText.js

King's Quest V Text Rendering

by sperske

HTML

<script src="http://thinkpixellab.com/pxloader/js/PxLoader.js"></script>
<script src="http://thinkpixellab.com/pxloader/js/PxLoaderImage.js"></script>
<input type='text' name='Say' placeholder="Type any quote from KQ6"/>

<canvas id="screen" width="300" height="200"></canvas>

CSS

input {
    width: 98%;
    margin-bottom: 10px;
}
#screen {
 width: 98%;
}

JavaScript

var screen = document.getElementById("screen").getContext("2d"),
    loader = new PxLoader(),
    font = {
        image: loader.addImage('http://media.sndtst.com/adventure/fonts/KQ6.png'),
        map: '©™!"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~',
        widths: {
          'a':5,'b':4,'c':4,'d':4,'e':4,
          'f':3,'g':4,'h':4,'i':1,'j':2,
          'k':4,'l':1,'m':7,'n':4,'o':4,
          'p':4,'q':4,'r':4,'s':4,'t':3,
          'u':5,'v':5,'w':5,'x':5,'y':4,'z':3,
          'A':4,'B':4,'C':4,'D':4,'E':4,
          'F':4,'G':5,'H':5,'I':3,'J':5,
          'K':5,'L':4,'M':5,'N':5,'O':4,
          'P':4,'Q':4,'R':4,'S':4,'T':5,
          'U':4,'V':5,'W':5,'X':5,'Y':5,'Z':5,
          ' ':3,',':2,'.':1,'!':1,'?':3,
          '&':3,'$':3,'#':5,'@':7,'[':2,
          '{':3,'}':3,'/':4,'\\':4,'=':3,
          '+':5,'-':3,'*':5,']':2,'\'':2,'"':3,
          '0':4,'1':3,'2':4,'3':4,'4':4,
          '5':4,'6':4,'7':4,'8':4,'9':4,
          '_':3,'~':4,'`':2,'|':1,'%':5,
          ':':1,';':2,'^':3,'<':3,'>':3,
          '©':6,'™':5,'(':3,')':3
        } 
    };

screen.imageSmoothingEnabled=false;

function drawText(text, context) {
    var offsetX = 0,
        offsetY = 0,
        lines = [],
        line = { words: [], size: 0},
        words = text.split(' '),
        l, w, c, word, i, widestLine = 0, currentLine;

    for(w = 0; w < words.length; w++) {
        word = {text: words[w], size: 0};
        for(c = 0; c < word.text.length; c++) {
            try {
                word.size += (font.widths[word.text.charAt(c)]+1);
            } catch(error) {
                word.size += font.widths['©']+1;
            }
        }
        if(line.size+word.size < 220) {
            line.words.push(word);
            line.size += word.size;
        } else {
            lines.push(line);
            if(widestLine < line.size) {
                widestLine = line.size;
            }
            line = { words:...