Playing with the Canvas Object

Back after a really busy week with a short article on drawing with the Javascript canvas object. This article describes my first foray into drawing in the browser, with some simple example code. What I’ve learned: canvas drawing presents some interesting interface possibilities that bear more investigation…

Sometimes I’m a little behind the current technology. For example, the <canvas> object has been in Firefox since v1.5 but I am just now looking into it. Until now I haven’t had a ton of uses for this kind of functionality but now I’m seeing a lot of potential there.

One thing I’ve wanted to do for a long time was be able to create an interface where boxes could be connected with lines, similar to a flowchart or Yahoo Pipes. This kind of capability would open up whole new possibilities for interfaces that are just too clumsy to implement in typical web pages with typical UI widgets.

My specific goal is to design a workflow editor that can be graphically manipulated similar to a Petri-Net editor (actually, Petri-Nets have long been my inspirado for a robust workflow system). But first, we’ve got to be able to draw boxes and connect them with lines. This is the type of thing that was very difficult if not nearly impossible before SVG and the Canvas Object were more widespread.

I began looking through the Mozilla Canvas Tutorial and playing around with this Canvas Shell they linked. After twiddling around with the little happy face that it draws, I inserted some actual code in there. I wanted to see how viable it was to draw some boxes and connect them with lines. I was especially interested in connecting them with bezier curves, since that would make it look all professional and stuff.

Two simple functions for boxes and lines (ctx is the canvas object):

function drawBox(x,y,color,size)
{
    var size = size || 10;
    ctx.strokeStyle = color || 'red';
    ctx.strokeRect(x-(size/2),y-(size/2),size,size);
}

function connectBoxes(x1,y1,x2,y2,color)
{
    ctx.strokeStyle = color || 'gray';
    ctx.beginPath();
    ctx.moveTo(x1,y1);
    ctx.bezierCurveTo(x1,y2,x2,y1,x2,y2);
    ctx.stroke();
}

Then, draw a few boxes, and connect them together:

ctx.clearRect(0,0,500,500);

drawBox(50,90);
drawBox(200,200,'blue',20);
drawBox(300,150,'gray');

connectBoxes(50,90,200,200);
connectBoxes(200,200,300,150);
connectBoxes(300,150,50,90,'orange');

The end result ends up looking like this:

Nice, and pretty! Considering how easy this was, I’m impressed with canvas drawing and excited to get to some more functional examples. Stay tuned!

Tags: ,

Comments are closed.