Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript - Splitting a tileset image to be stored in 2D Image() array

Let's say I have this image:

enter image description here

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?

like image 551
test Avatar asked Jul 18 '12 02:07

test


1 Answers

I would..

  • Figure out how many tiles wide and high this image is
  • Draw the image to a canvas in memory, and use the context to get image data.
  • Loop through and subimage each tile, storing in an array.

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);
  }
like image 125
Aesthete Avatar answered Oct 17 '22 03:10

Aesthete