Fork me on GitHub

CD2D




C2D2 (See 2D Too) is a light-weight wrapper for HTML5 Canvas, providing jQuery-style chaining in a light package, along with a few light but useful utilities.

Usage

Including the file(s)

The first file (also repackaged into C2D2 for convenience), explorercanvas, is conditionally included for compatibility with IE versions < 9, though with limited support in some areas. See explorercanvas for details.

Creating a context (and a canvas element if not yet created):

Getters (vs. Setters):

Comparison of direct canvas wrappers to C2D2's custom utility methods:

Chaining:

Usage with Node.js Server-Side JavaScript

Note that this usage requires node-canvas. Also note that C2D2 will generate a PNG file when the (equivalent) 'path' or 'fileStream' option is included, and the directory is never cleaned up by C2D2. Besides creating new files, it will also always rewrite the file if already present. I have not worked closely with this functionality, so please report any bugs to me at brettz9 at the site Yahoo.

Additional utility methods

There are also a few static class methods, C2D2.randomNumber, C2D2.randomColor, and C2D2.getCSSPropertyValue, with the latter used for separation of concerns, allowing convenient detection of CSS style rules specified in stylesheets and applying them as arguments to canvas methods (e.g., for detecting the beginning or end color of a JavaScript-powered transition).

API Design

All HTML5 Canvas (2D Context) methods and properties are wrapped, as is the Canvas element itself, and convenient (hopefully more intuitively named) wrapper methods are also available, with the character '$' preceding the method names in the case of such utilities (e.g., $line wraps lineTo, $lineColor wraps strokeStyle, etc.). You can always access the canvas and 2D context methods and properties, with the small difference that everything (besides getter properties and methods which are designed to return their own special content) can be chained, and that properties are accessible via methods, of the same name, with a no-argument-call being treated as a getter and everything else as a setter.

Background and Intent

Although this is definitely still a work in progress (feedback welcome), since I saw no other low-level canvas libraries out there (i.e., lower level than say building charts and specific objects), I thought I'd make this one available. This was most recently motivated by nostalgia for the simplicity of HIRES and LORES Apple Basic commands and the fun experimentation with randomizing colors, and by the chaining popularized by jQuery. Enjoy!