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

前端 未结 2 1146
盖世英雄少女心
盖世英雄少女心 2021-01-18 06:08

Let\'s say I have this image:

\"enter

and I have this 2D array tiles[]

2条回答
  •  感动是毒
    2021-01-18 06:49

    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

提交回复
热议问题