2

I would like to know if it is possible to use canvases and javascript to scan an image for certain pixel colors and use them to make a map. e.g: find #ff0000 and set it to the number 1 on the map and set #000000 to 2 and so on to make a map like:

var map = [
    [1,1,1,1,1],
    [1,0,0,0,1],
    [1,0,2,0,1],
    [1,0,0,0,1],
    [1,1,1,1,1]
];

So basically i want to know how to get the code to read an image and find the colors i want it to search for and then plot them out in a variable

stewe
  • 41,820
  • 13
  • 79
  • 75
user1306988
  • 43
  • 1
  • 4

2 Answers2

5

This should be a good start.

var zeroFill = function(num, padding) {
    return Array(padding + 1 - (num + '').length).join('0') + num;
};

var hexColorsToId = {
        'ff0000': 1,
        '000000': 2 
        /* ... */
    },
    map = [],
    canvas = document.createElement('canvas'),
    ctx = canvas.getContext('2d'),
    image = new Image;

image.onload = function() {
    canvas.width = image.width;
    canvas.height = image.height;
    ctx.drawImage(image, 0, 0, image.width, image.height);

    var data = ctx.getImageData(0, 0, canvas.width, canvas.height).data;

    for (var i = 0; i < data.length; i += 4) {
        var red = zeroFill(data[i].toString(16), 2),
            green = zeroFill(data[i + 1].toString(16), 2),
            blue = zeroFill(data[i + 2].toString(16), 2),
            hex = red + green + blue;

        if (hexColorsToId.hasOwnProperty(hex)) {
            map.push(hexColorsToId[hex]);
        }
   }
};

image.src = '/img/logo.png';​
alex
  • 479,566
  • 201
  • 878
  • 984
  • thanks for the help but i have to ask, what is the var zeroFill doing? i understand it all except zeroFill, what will happen depending on the num and padding values? thanks – user1306988 Apr 02 '12 at 07:08
  • @user1306988 If you get `0` and `toString(16)`, it's still `0`. However, when you see `0` in a `rrggbb` grouping, it always has a preceding `0`. So it takes an argument such as `0` and ensures it always has the leading zero, e.g. `00` or `04`. – alex Apr 02 '12 at 07:20
  • sorry for asking stupid but do i just leave num and padding as they are or is there a value i should be setting them? and if so how can i know what to be setting them – user1306988 Apr 02 '12 at 07:51
  • @user1306988 The code is already calling it inside of the loop that iterates over the pixel data. – alex Apr 02 '12 at 08:18
  • @alex Is it possible to get the image data without drawing the image to the context? – Ricardo Sanchez May 21 '12 at 16:15
  • @RicardoSanchez It might be, I haven't looked into that before, so I'm not 100% sure if it's possible. – alex May 21 '12 at 23:38
-1

Off course you can work with single pixels in the canvas. Here's a tutorial: http://tutorials.jenkov.com/html5-canvas/pixels.html

But you can find many others on the web!

Saturnix
  • 10,130
  • 17
  • 64
  • 120