简体   繁体   English

如何在多个图像而不是一个图像上运行此javascript?

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

I ran through this: PUZZLE CREATING TUTORIAL and completed the puzzle. 我经历了这个过程: 拼图创作教程 ,完成了拼图。 I'm trying to have the same script run on more than one img on a page. 我试图让同一脚本在页面上的多个img上运行。 I tried running some of it through a loop: 我尝试通过循环运行其中的一些:

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);

}

and I've gotten to a point where I can print the 'i'th picture in the 'i'th canvas id, but it will only print one puzzle at a time and not more. 现在我可以在'i'canvas id中打印'i'图片,但是一次只能打印一个拼图,不能打印更多。

Everything in the puzzle code is not set up to handle multiple puzzles. 拼图代码中的所有内容均未设置为可以处理多个拼图。 You'll actually need to make way more changes than that to have the puzzle get rendered correctly. 实际上,您需要进行的更改要多得多,才能正确呈现拼图。

What you should probably do is make a new makePuzzle function, that sets up variables for the rest of the functions to use, and then have them accept arguments, instead of relying on the things that are in the global scope.. 您可能应该做的是制作一个新的makePuzzle函数,该函数为其余函数设置变量以供使用,然后让它们接受参数,而不是依赖全局范围内的事物。

for an example (This won't work unchanged, but should illustrate my point): 举一个例子(这将不会起作用,但应该说明我的观点):

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM