问题
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
回答1:
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';
回答2:
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!
来源:https://stackoverflow.com/questions/9969673/use-canvas-and-javascript-to-read-the-pixel-colors-of-an-image