The Pixelize jQuery Plugin

Published March 22, 2014 by CSS Newbies.

I am unabashedly and unreasonably fond of pixel art. It evokes a nostalgia for a simpler time (tinted generously with the fog of many years) when I would rush home from school, fire up my Nintendo, and try to rescue Zelda from the evil clutches of Ganon.

To that end, I’ve created a simple jQuery plugin that can turn a JavaScript array into CSS pixel art. It looks like this:

See the Pen Pixelize jQuery Plugin by Rob Glazebrook (@rglazebrook) on CodePen.

And it works like this:

First, you’ll need an array (of arrays) to work with. Each item in the first array acts like a row in our art, each item within the nested array acts like a column in our row. It looks like this:

var my_array = [
  ['#f00','#0f0','#f00'],
  ['#0f0','#f00','#0f0']
];

That would create a 3-square-wide by 2-square-tall series of alternating red and green pixels. Sorta boring, but this is an example.

In my experience, it’s way faster to create some color variables up front and then use those to populate the array you’re going to use. It also provides some protection against typos. So our code would now look like this:

var r = '#f00',
g = '#0f0',
my_array = [
  [r,g,r],
  [g,r,g]
];

Much easier to read. You can also leave spaces empty in the array to create empty pixels.

Once you have an array, you’re done with the hard part. Now you just create an element in your HTML you want to become pixel art:

<div class="pixely"></div>

And then call the jQuery plugin like so:

$('.pixely').pixelize(my_array);

And you’re done!

Gotchas and Tips

  • The “pixels” in your art are 1em square. To change the size of the pixels, just set a font-size on the element you’re pixelizing.
  • Your element will be resized to 1em square. This is now the top-left pixel. To position your pixel art, provide some margins or positioning via CSS.

Download and Example

I’ve put the plugin up on GitHub. Here it is.

The example of usage is on CodePen. Check it out.

3 Responses

  1. Pingback: Bouncing Balls in the HTML5 Canvas | Web Design Articles From An Actual Living Web Professional

  2. Pingback: Simple Table Column Highlighting - Orlando Web Design - Orlando Web DesignOrlando Web Design

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>