« Home | Breakout » | iWoz Standing Next to Steve Wozniak » | Fishbowl » | Blackjack » | If You Don't Own, You Are Owned » | My Place In Cyberspace » | Windows Live Writer » | Playing With A Full Deck » | All Your Scooter Are Belong To Us » | Chatter Box Source »

JavaScript Graphics Library

Update
Looks like Lord Vikram took my Graphic class and created a JavaScript whiteboard. Now I'd like to see him AJAX it.

Original Post
I know it's probably been done before, but I wanted to take a crack at writing the rudiments of a JavaScript graphics library. If you've spent any time using JavaScript, you know there's no simple way to draw vector images on the screen. As you might expect, my solution abuses the DOM by creating thousands of little DIV elements. It's slow, especially when drawing a relatively complex shape such as a circle.



To get started, download the .js and .css files and reference them in your HTML as follows:

<link rel="stylesheet" href="graphic.css"/>
<script src="graphic.js"></script>

After that, create a new instance of the Graphic class. Each instance encapsulates a DIV element which may be placed within your document however you wish. Here's a short example that creates a 200 by 100 pixel canvas, draws a few shapes on it, and then adds the DIV to the DOM:

var g = new Graphic(200, 100);
g.setColor("red");
g.drawPoint(100, 50);
g.drawLine(10, 10, 75, 80);
g.drawRect(180, 70, 30, 15);
g.drawCircle(100, 50, 50);
document.body.appendChild(g.getDOMElement());

And here's want you'd see:



There's lots of room for improvement, so please feel free to modify.

........................................................................................................................................................................