putImageData不会绘制到画布

时间:2012-07-19 03:34:37

标签: javascript jquery html5 canvas

分割拼贴http://mystikrpg.com/images/all_tiles.png

它仍然无法吸引<canvas>我知道它会被放入tileData[],因为它会在console.log(tileData[1])中输出ImageData。

$(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);
    }
    }

1 个答案:

答案 0 :(得分: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 );
  }

};

没有必要测试'全部加载',因为它只是一个你正在拆分的图像。