HTML and CSS Reference
In-Depth Information
You're going to start by defining four variables:
backgroundTexture = new Image() will be used to store your image
pixelGroups = {} will be used to group pixels of a same color together
colourIndexes = ['4766b5', '3e589a', '354c87', '2e4276', '2a3c6c', '22325a'] will
be your palette, as shown in Figure 8-13
currentColourOrder = colourIndexes.slice(0) will be used to cycle through all the colors
in your palette
Then, as soon as your image is loaded, you'll need to read all the pixels of the image to group them together in the
pixelGroups variable, like this:
// Load the background texture
backgroundTexture.src = 'texture.gif';
backgroundTexture.addEventListener('load', function() {
var i = 0,
j = 0,
backgroundTextureData = null;
In order to read the colors of a given pixel, you'll need to resort to using a method of the Canvas object called
getImageData() , but before doing that, you'll need to paint the texture in the canvas first, as shown in Listing 8-29.
Listing 8-29. Painting the Texture in the Canvas Object
// Paint the image on the canvas for the first time)
// Grab the image data using the getImageData() method
backgroundTextureData = ctx.getImageData(0, 0, backgroundTexture.width, backgroundTexture.height);
backgroundTextureData =;
// Resize the canvas to the size of the image
canvas.width = backgroundTexture.width;
canvas.height = backgroundTexture.height;
Here comes the interesting part; you'll need to cycle through each pixel of the image to get the color data, as
shown in Listing 8-30.
Listing 8-30. Cycling Through each Pixel
// Group pixels by colour
// (keep in mind that there's a much faster way to cycle through
// all these pixels using typed arrays, I'm keeping it "simple" for
// the sake of clarity
for ( ; i < backgroundTexture.height ; ++i ) {
for ( j = 0 ; j < backgroundTexture.width ; ++j ) {
Search WWH ::

Custom Search