Archive

Archive for September, 2011

Canvas Tile System

September 15th, 2011 No comments

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:
Desert Sprite Map

( 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

Categories: JavaScript Tags:

Canvas Pixel Manipulation a’ la Quick and Dirty

September 9th, 2011 No comments

In a recent prototype I attempted to load in a PNG onto a canvas, change the image to a silhouette, as well as create a desaturated version, cache all three (including the initial state) sets of pixel data, and swap them out interchangeably. Then I wanted to spit the data back out into something I could incorporate into the DOM.

Here’s what I came up with: Canvas Pixel Manipulation

Categories: JavaScript Tags: