Musings of a Fondue

Canvas Cycle - Part 2

Original Date: July 26, 2013

Drawing an image using pixel data

The more I looked at the color and pixel data in the image.php file, the more convinced I became that I could write something that could draw the image. The pixels array in the file was in a grid-like format exactly 640 elements across and 480 down (corresponding to the image dimensions of 640 x 480). I played around with canvas to see what I could do.

To implement, I represented each pixel as a 1x1 rectangle. I also converted the pixels array into a two-dimensional array with each sub-array representing a horizontal row of 640 pixels. This is much like how the colors array is two-dimensional with each sub-array representing the three components (red, green, blue) of a single color [r,g,b].

A couple of hours of playing around became nine lines of code.

//add rgb() syntax to colors
for (i= 0; i < 256; i++ ) {
    colors[i] = "rgb(" + colors[i] + ")";

//initialize canvas
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
var h = w = 1;

//draw pixels
for (y = 0; y < 480; y++ ) {
    for (x = 0; x < 640; x++) {  

And here is the live result