Greg Houston’s uber-cool MochaUI has led me to experiment with the canvas element the last few days.

I first saw MochaUI sometime in 2007. While I was duly impressed, I couldn’t quite find a use for it and filed it away in my bottomless “play with this later” drawer.

Recently at work I realized I needed a good modal window that was more extensible than JavaScript’s built-in confirm and prompt windows. MochaUI looked like a handy way to get slick modal windows into my project, but I soon realized that MochaUI is designed to do much, much more than I need, and therefore is (for my purposes) bloated. So, in typical DIY fashion here at pipwerks, I decided to borrow a page from Greg’s book and make my own MochaUI-inspired modal window using the canvas element, CSS, HTML, and MooTools.

Before I could get into the full modal window code, I needed to understand the canvas element, and learn how to manipulate it. Luckily for me, it isn’t much different than ActionScript’s drawing API. After evaluating what I’d need for my little modal window, I whipped up a MooTools-based JavaScript class that produces canvas rectangles in the blink of an eye. Check out the test suite.

Here’s how you’d instantiate a plain-jane rectangle with no stroke and a pink fill:

var canvas = new Element("canvas", {width:300, height:200}).inject(document.body); var rect = new Rectangle({ canvas: canvas width: 300, height: 200, x: 0, y:0, fill: "#F36" });
Code language: JavaScript (javascript)

Want rounded corners? Just add a radius parameter:

var rect = new Rectangle({ canvas: canvas width: 300, height: 200, x: 0, y:0, fill: "#F36", radius: 9 });
Code language: JavaScript (javascript)

As demonstrated by the test suite, the class includes the ability to specify the radius of each corner, the fill type and color (solid or linear gradient), and the stroke weight and color (including linear gradient).

For those of you unfamiliar with the canvas element, there are a host of additional options I chose not to build into my class, including join type for lines, radial gradients, and image backgrounds. For the purposes of my modal window, I didn’t need that stuff and wanted to keep it simple (and smaller file size). Feel free to modify the class for yourself, though.

Sometime in the next day or two, I’ll write about my modal window and provide test links. I’ll also cover the fugly hack required to get Internet Explorer to work with canvas.

Until then…

UPDATE: Read about the Modal class here.

PS: Disclaimers:

  1. If you’re wondering why I didn’t include a sample of the class in action on this page, my WordPress install uses jQuery, which conflicts with MooTools. I didn’t feel like fighting it tonight.
  2. I don’t write JS classes often, so I’m sure mine could use some cleanup. Feel free to make suggestions!

Similar Posts