Let\'s say I have this image:
and I have this 2D array tiles[]
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);
}
ok I did this on my localhost: it should give you a base at least. I think you should be able to use this straight outta the box but you might have to make a few calculation adjustments for it depending on what you want. I just don't think it's neccessary to spend thee time to perfect it to your example:
You'll obviously have to point the image to your own image.
<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
var canvas = document.getElementById('fakeCanvas');
var ctx = canvas.getContext('2d');
var img = new Image();
img.src = '/theImage.png';
var tiles = [];
var imageTileNumWidth = 23;
var imageTileNumHeight = 21;
img.onload = function(){
var imageWidth = img.width;
var imageHeight = img.height;
sndCanvasWidth = imageWidth/imageTileNumWidth;
sndCanvasHeight = imageHeight/imageTileNumHeight;
canvas.width = imageWidth;
canvas.height = imageHeight;
ctx.drawImage(img,0,0,imageWidth,imageHeight);
var sndCanvas = document.getElementById('drawCanvas');
sndCanvas.width=sndCanvasWidth;
sndCanvas.height=sndCanvasHeight;
var i=0;
var j=0;
var t=0;
for(i=0;i<imageWidth;i+=sndCanvasWidth){
for(j=0;j<imageHeight;j+=sndCanvasHeight){
var myImageData = ctx.getImageData(j,i,sndCanvasWidth,sndCanvasHeight);
var ctx2 = sndCanvas.getContext("2d");
ctx2.putImageData(myImageData,0,0);
tiles.push(myImageData);
}
}
};
});
</script>
</head>
<body>
<canvas id="fakeCanvas"></canvas>
<canvas id="drawCanvas"></canvas>
</body>
</html>