Let's say I have this image:
and I have this 2D array tiles[]
.. and using Image()
function... how can do I use the (what I assume be best way?) for
loop to add each tile into the array
so tile[0]
through however many there are is read and used as Image()
objects later to be painted on HTML5 canvas?
I would..
Assuming:
imageWidth, imageHeight, tileWidth, tileHeight
All describe what their names suggest, and:
EDIT: Added image load as per comment, fixed wrongly name ImageWidth
and ImageHeight
to imageWidth
and imageHeight
EDIT: Performing code inside imageObj.onload
as the image is drawn here, drawImage() from origin (0,0)
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
var imageObj = new Image();
imageObj.src = "tilesetImageLocationHere";
imageObj.onload = function() {
ctx.drawImage(imageObj, 0, 0);
Then, split up your image into a list of tile data..
var tilesX = imageWidth / tileWidth;
var tilesY = imageHeight / tileHeight;
var totalTiles = tilesX * tilesY;
var tileData = new Array();
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(ctx.getImageData(j*tileWidth, i*tileHeight, tileWidth, tileHeight));
}
}
//From here you should be able to draw your images back into a canvas like so:
ctx.putImageData(tileData[0], x, y);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With