gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 09:06:45 26 4
gpt4 key购买 nike

我经历过这个: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 个 Canvas id 中的第 'i 张图片的地步,但它一次只能打印一个拼图,而不是更多。

最佳答案

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

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

关于javascript - 如何在多张图像而不是一张图像上运行此 JavaScript?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16950563/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com