1

我浏览了这个:PUZZLE CREATING TUTORIAL并完成了拼图。我试图在一个页面上的多个 img 上运行相同的脚本。我尝试通过循环运行其中一些:

var i;
for(i=1; i<3; i++){

function init(){

    _img = new Image();
    _img.addEventListener('load', onImage, false);
    _img.src = "images/"+i+".png" 
}

function onImage(e){
    _pieceWidth = Math.floor(_img.width / PUZZLE_DIFFICULTY)
    _pieceHeight = Math.floor(_img.height / PUZZLE_DIFFICULTY)
    _puzzleWidth = _pieceWidth * PUZZLE_DIFFICULTY;
    _puzzleHeight = _pieceHeight * PUZZLE_DIFFICULTY;
    setCanvas();
    initPuzzle();
}

function setCanvas(){ 
    _canvas = document.getElementById(""+i+""); 

    _stage = _canvas.getContext('2d');
    _canvas.width = _puzzleWidth;
    _canvas.height = _puzzleHeight;
    _canvas.style.border = "2px solid red";

}
    console.log(i);

}

而且我已经到了可以在第 i 个画布 ID 中打印第 i 个图片的地步,但它一次只能打印一个拼图,而不是更多。

4

1 回答 1

0

谜题代码中的所有内容都没有设置为处理多个谜题。实际上,您需要进行更多更改才能正确渲染拼图。

您可能应该做的是创建一个新makePuzzle函数,为其余函数设置变量以供使用,然后让它们接受参数,而不是依赖于全局范围内的东西。

举个例子(这不会改变,但应该说明我的观点):

function makePuzzle(puzzleId, difficulty) {
  var image = new Image();
  image.addEventListener('load', function() {
    makePuzzleForImage(image);
  }, false);
  image.src = "images/"+puzzleId+".png" 
}

makePuzzleForImage(image) {
  var pieceWidth = Math.floor(image.width / difficulty)
  var pieceHeight = Math.floor(image.height / difficulty)
  var puzzleWidth = pieceWidth * difficulty;
  var puzzleHeight = pieceHeight * difficulty;

  var canvas = document.getElementById(""+puzzleId+""); 
  var stage = canvas.getContext('2d');
  canvas.width = puzzleWidth;
  canvas.height = puzzleHeight;
  canvas.style.border = "2px solid red";
  // this also needs to be made so it can accept arguments, but I didn't
  // do that for you since it'll take more time:
  // initPuzzle();
}

for (var i=1; i<3; i++) {
  makePuzzle(i, PUZZLE_DIFFICULTY);
}
于 2013-06-06T09:46:13.623 回答