0

拆分图块集后http://mystikrpg.com/images/all_tiles.png

它仍然不会绘制到<canvas>我知道它被放入的tileData[]因为它输出 ImageData 在console.log(tileData[1]).

$(document).ready(function () {

var tileWidth, tileHeight
ImageWidth = 736;
ImageHeight = 672;
tileWidth = 32;
tileHeight = 32;

    console.log("Client setup...");
    canvas = document.getElementById("canvas");
    canvas.width = 512;
    canvas.height = 352;
    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;        
    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); // 483
    console.log(tileData[1]); // > ImageData
    startGame();
    }
    };

});

var startGame = function () {

   console.log("Trying to paint test tile onto convas...");

    try {
    context.putImageData(tileData[0], 0, 0);
    } catch(e) {
        console.log(e);
    }
    }
4

1 回答 1

1

当您最初将图像绘制到画布时,您为什么会:

context.drawImage(imageObj, ImageWidth, ImageHeight);

看起来您可能对参数感到困惑,并试图用 ImageWidth、ImageHeight 填充该区域...相反,将其绘制为 0,0

context.drawImage(imageObj, 0, 0);

这是您的代码稍作调整:

var tileData = [];

var tileWidth, tileHeight
var ImageWidth = 736;
var ImageHeight = 672;
var tileWidth = 32;
var tileHeight = 32;
var tilesX;
var tilesY
var totalTiles;
canvas = document.getElementById("canvas");
canvas.width = ImageWidth;
canvas.height = ImageHeight;
context = canvas.getContext("2d");

var imageObj = new Image();
imageObj.src = "all_tiles.png";
imageObj.onload = function() {
  context.drawImage(imageObj, 0, 0);
// draw the image to canvas so you can get the pixels context.drawImage(imageObj, 0, 0);

  tilesX = ImageWidth / tileWidth;
  tilesY = ImageHeight / tileHeight;
  totalTiles = tilesX * tilesY;
  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));
    }
  }

  // test it...
  // blank the canvas and draw tiles back in random positions 
  context.fillStyle = "rgba(255,255,255,1)";
  context.fillRect(0,0,canvas.width, canvas.height);
  for ( i = 0; i < 20; i++ ) {
    context.putImageData(tileData[ i ], Math.random() * canvas.width, Math.random() * canvas.height );
  }

};

无需测试“全部加载”,因为它只是您要拆分的一张图像。

于 2012-07-19T03:58:39.893 回答