我如何在多个图像上运行这个javascript而不是一个

How do I run this javascript on multiple images instead of just one?

本文关键字:一个 javascript 运行 图像      更新时间:2023-09-26

我浏览了这个: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' th画布id中打印' I' th图片,但它一次只能打印一个谜题,而不是更多。

谜题代码中的所有内容都没有设置为处理多个谜题。实际上,你需要做更多的改变,以使谜题得到正确渲染。

你可能应该做的是做一个新的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);
}