Reputation: 11
I'm trying to get the pixel array from a 16 x 16 image with getImageData(). I will use that to make a map from larger tiles. For example, if the color of the the top left pixel is green, then on my actual game map there will be a grass tile at 0, 0. My code for getting the array:
function getData() {
map = new Image();
map.src = "./res/maps/sample.png";
ctxTemp.drawImage(map, 0, 0);
var temp = ctxTemp.getImageData(0, 0, 16, 16).data;
console.log(temp);
for (var i = 0; i < temp.length; i+=4) {
var red = temp[i];
green = temp[i + 1];
blue = temp[i + 2];
alpha = temp[i + 3];
}
}
Upvotes: 0
Views: 599
Reputation:
Must wait until the image is loaded. Works fine after attaching the code to onload
.
function getData() {
var map = new Image();
map.onload = function() {
var canvas = document.getElementsByTagName("canvas")[0];
var ctx = canvas.getContext("2d");
ctx.drawImage(map, 0, 0);
var temp = ctx.getImageData(0, 0, 16, 16).data;
console.log(temp);
for (var i = 0; i < temp.length; i += 4) {
var red = temp[i];
green = temp[i + 1];
blue = temp[i + 2];
alpha = temp[i + 3];
}
};
map.src = "./res/maps/sample.png";
}
window.onload = getData;
Upvotes: 1