我跑过这个: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);
}
我已经达到了可以在第一个画布ID中打印第一张照片的地步,但它只打印了一个谜题时间而不是更多。
答案 0 :(得分: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);
}