Canvas with Text 1

Posted by Oliver on February 27, 2006

The two times that I’ve used the WHATWG canvas element recently, I’ve wanted a canvas with string rendering. The most recent time that I’ve used the OpenLaszlo drawview class (which has substantially the same API), I’ve wanted string rendering too.

The graph in reAnimator is a drawview, but with text labels for the edges. And the graph and parse tree in the Graph and Parse tabs of reMatch both use WHATWG canvas for lines, but text for labels. (These tabs are only visible in Firefox, for now.)

TextCanvas.js implements the canvas context extended with labels, for DHTML. And “textdrawview.lzx” implements drawview extended with labels. They share the same API, so that I can write graphics libraries (such as graph drawing) that work with both DHTML and OpenLaszlo. That API is described here.

The first example below is an OpenLaszlo application that uses textdrawview; view source here.

If you’re using Firefox, you can also view the DHTML example. This uses TextCanvas; open it in a separate page here.

Files:
* textcanvas.jsDHTML implementation
* textcanvas-example.htmlDHTML example (shown running above)
* textdrawview.lzx — OpenLaszlo implementation
* textdrawview-example.lzx — OpenLaszlo example (shown running above)
* textcanvas-apiAPI documentation

Some example code:

// <div id="canvasContainer"></div>
var container = document.getElementById('canvasContainer');
var textCanvasController = new TextCanvasController(container);
var ctx = textCanvasController.getContext('2d');
ctx.moveTo(0, 0);
ctx.lineTo(100, 100);
ctx.stringStyle.color = 'red';
ctx.drawString(0, 0, "red");
ctx.stringStyle.color = 'blue';
ctx.drawString(100, 100, "blue");

Trackbacks

Trackbacks are closed.

Comments

Comments are closed.

  1. Mihai Parparita Tue, 28 Feb 2006 12:10:16 PST

    Conincidentally, I’ve been working on a similar idea:

    http://persistent.info/archives/2006/02/26/canvas-text

    I took a pretty different approach; text is rendered inside the canvas with the help of a font texture. This means you can apply the canvas’s transforms to the text, but performance isn’t as good.