Canvas Tile System
Here’s something quick that I put together to see how easily I could create a Tile System (as in 2d sprite map for games) using JavaScript and Canvas.
First I set out to create a system for loading, caching, and retrieving the tiles. Here’s what I came up with:
// Allows you to load image sprite and then make cached tiles // that can be retrieved var TileLibrary = function (img) { var oTileLibrary = {}, elCanvas = document.createElement('canvas'), cxCanvas = elCanvas.getContext('2d'); elCanvas.width = img.width; elCanvas.height = img.height; cxCanvas.drawImage(img, 0, 0, img.width, img.height); return { makeType: function (name, x, y, width, height) { oTileLibrary[name] = cxCanvas.getImageData(x, y, width, height); }, getTileData: function (name) { return oTileLibrary[name]; } }; };
This allows me to take an Image object and turn pieces of it into data that canvas can understand. Usage would look something like this:
// img is a preloaded image object var oTileLibrary = new TileLibrary(img); // cuts out a chunk of the image at (0, 0) with dimensions 64x64 and caches it oTileLibrary.makeType("FloorTile", 0, 0, 64, 64); // gets the ImageData out of cache and ready to be dumped into a canvas var tFloorTile = oTileLibrary.getTileData("FloorTile"); // inserts that floor tile into its final destination myCanvas.putImageData(tFloorTile, 0, 0);
I ended up borrowing this image for my prototype:

( http://www.lostgarden.com/2006/02/250-free-handdrawn-textures.html )
I cut out the third tile and the fourth tile, and arranged them in a 3×3 grid, with the middle tile being the little circle looking thing.
Check out the sample here: Tile System Prototype