<!-- Some kind of exercise in reflexivity, displaying its own source code in
the font it contains by default, which I designed this afternoon.  Imperfect;
needs to wait for font to load. On the web at
http://canonical.org/~kragen/sw/dofonts.html
-->

<title>Fixed-width font rendering with &lt;canvas&gt;</title>
<img src="data:image/png;base64,
iVBORw0KGgoAAAANSUhEUgAAAFAAAAAkAQMAAAAkbC85AAAAAXNSR0IArs4c6QAAAAZQTFRF////
AAAAVcLTfgAAAWZJREFUGNNjYBT1925JlmFgYGJgFH0hxXOww4GBjYGR0d/4wME5Dyp4GBgYnyY1
HOxwYpwBEvUGirIxTmBgYGBhYEhmAIGPtq+i75V3ODPLMUxW0XISCmlgq5zEsJEnv/pYeQMPwzGG
iZJKXD4BHW6VLQyf9z6qPlHecJiZAQFYGL7vfV997/peHa84hilb1yZLXObMqQ5i2L63t3jWZ84z
1ZcYWoCiUpc1fbwuMXwBqpW7vjMfqBYJAE3ICgrZ98KygeHK1rasoPK2M9IHgGqfZd9T5jkm5cBw
bIVa5rxiicMSDAzH1z6rnBRs99ACqK8Bqt+eQUGBkeFAIycbkGOgwFjQ18DoAmQy73geeeuz5JHq
ewxsa3sL+iZyplQFgUQtmiav1Ie6gY/BAuYTIHhUfA5IHgFimyYBDobvO/u9Ar/0NkjIMUxZcMT7
avqMJgEZhu8L2yvnf9jzqICDoQHkBmYgwQcApJKC4Obqr0wAAAAASUVORK5CYII=
" id="font" />
<textarea id="input">
Enter text here to render.
</textarea>
Load other font (Twitter usericons work well): <input id="fonturl" />
<p>
<canvas width="512" height="512" id="c"></canvas>
<script src="jquery-1.2.6.js"></script>
<script>
// Render text with a fixed-width font.

// Definition of fixed-width font file format:
var charsPerLine = 16
  , startCharCode = 32
  , endCharCode = 128           // one greater than last glyph

    // DOM elements:
  , cv = $('#c')[0]
  , cx = cv.getContext('2d')
  , font = $('#font')[0]
  , input = $('#input')
  , fonturl = $('#fonturl')

function renderText(text) {
  var xx = 0
    , yy = 0
    , lines = (endCharCode - startCharCode) / charsPerLine
    , width = Math.floor(font.width / charsPerLine)
    , height = Math.floor(font.height / lines)

  cx.drawImage( font
              , 0, 0, width, height
              , 0, 0, cx.canvas.width, cx.canvas.height
              )

  for (var ii = 0; ii < text.length; ii++) {
    var cc = text.charCodeAt(ii)
      , fontIndex = cc - 32
      , line = Math.floor(fontIndex / charsPerLine)
      , col = fontIndex % charsPerLine
      , sx = col * width
      , sy = line * height

    if (cc >= startCharCode && cc < endCharCode) {
      cx.drawImage( font
                  , sx, sy, width, height
                  , xx, yy, width, height
                  )
      xx += width
    } else if (cc === '\t'.charCodeAt(0)) {
      do {
        xx += width
      } while (xx/width % 8 !== 0)
    }

    if (xx > cx.canvas.width - width || cc === '\n'.charCodeAt(0)) {
      xx = 0
      yy += height
      if (yy > cx.canvas.height) {
        break;
      }
    }
  }
}

input.val(document.body.innerHTML)
renderText(input.val())
input.keyup(function() { renderText(input.val()) })
fonturl.keyup(function() {
  font.src = fonturl.val()
  renderText(input.val())
})
</script>
-- 
To unsubscribe: http://lists.canonical.org/mailman/listinfo/kragen-hacks

Reply via email to