I am trying to break a spritesheet and well, it’s not putting it into a 2D array like it should. At the end of my code, near the console.log, it spits out ImageData…but when it tries to putImageData… I get Uncaught TypeError: Type error
Help?
and here’s my code:
$(document).ready(function () {
console.log("Client setup...");
canvas = document.getElementById("canvas");
context = canvas.getContext("2d");
canvas.tabIndex = 0;
canvas.focus();
console.log("Client focused.");
var imageObj = new Image();
imageObj.src = "./images/all_tiles.png";
imageObj.onload = function() {
context.drawImage(imageObj, imageWidth, imageHeight);
};
var allLoaded = 0;
var tilesX = ImageWidth / tileWidth;
var tilesY = ImageHeight / tileHeight;
var totalTiles = tilesX * tilesY;
var tileData = [totalTiles]; // Array with reserved size
for(var i=0; i<tilesY; i++)
{
for(var j=0; j<tilesX; j++)
{
// Store the image data of each tile in the array.
tileData.push(context.getImageData(j*tileWidth, i*tileHeight, tileWidth, tileHeight));
allLoaded++;
}
}
if (allLoaded == totalTiles) {
console.log("All done: " + allLoaded);
console.log(tileData[1]);
context.putImageData(tileData[0], 0 ,0); // Sample paint
}
});
error happens at context.putImageData(tileData[0], 0 ,0); // Sample paint
Here is example fiddle of code above http://jsfiddle.net/47XUA/
Your problem is that the first element of
tileDatais not anImageDataobject, it’s a plain number! When you initialized your array you used:This means that
tileData[0]is equal to the value oftotalTiles, which is the number483. You are providing a number instead of anImageDataobject toputImageData, and the browser is throwing an error in confusion. If you look at any other element in the rest of your array, you’ll see it is successfully being populated withImageDataobjects as you expect; only the first element in the array is a number.You probably meant to do:
which would create an array with the specified
lengthproperty, instead of setting the first value in the array to a number. Personally, I would run some performance tests to see if that is even useful; you may be just as well usingvar tileData = [];