2013-06-05 30 views
1

我跑過了這個:PUZZLE CREATING TUTORIAL並完成了這個謎題。我試圖讓相同的腳本在頁面上運行多個img。我試圖通過一個循環中運行一些吧:如何在多個圖像上運行此JavaScript而不是僅運行一個?

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個畫面」第i個帆布ID打印的,但它只能打印一個一次謎題,而不是更多。

+1

你在哪裏實際上調用每個的功能是什麼?從你在這裏展示的內容來看,你循環了每個函數的聲明,但並沒有實際調用一個東西。從循環中取出函數聲明並傳遞'i'。例如'for(i = 1; i <3; i ++){init(i);}' – scrappedcola

+0

@scrappedcola在第二個函數中調用initPuzzle()函數,並導致構建拼圖的許多其他函數。我調用了'for(i = 1; i <3; i ++){init(i);}'並且按照你的建議從循環中取出了函數,它仍然和以前一樣,但是隻有一個難題一個時間,沒有更多。 – Squirrl

回答

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); 
} 
+0

謝謝。這是一個漫長的過程,但是你帶領我走向正確的方向。我把所有的變量放到一個對象中,然後在onPuzzleClick(e)上調用它。這個'e'參數混淆了我的bejesus,但我最終得到了它。 – Squirrl

+0

很酷,很高興我能幫上忙。 – arnorhs

相關問題