Image.onload()的JavaScript循环/范围问题 [英] JavaScript loop/scope issue with Image.onload()
问题描述
我正在尝试使用JavaScript循环一个对象,并将该对象的所有子对象添加到HTML5画布。
I'm trying to loop through an object with JavaScript and add all the subobjects from that object to a HTML5 canvas.
画布位正在工作,没有问题,但由于某种原因,我的所有图像最终都是相同的大小 - 最后一个子对象'背景'的大小。我假设它与我的循环范围和'this'有关,但我真的不知道要改变什么;
The canvas-bit is working, no problem with that, but for some reason all my images end up being the same size - the size of the last subobject 'background'. I'm assuming that it has to do with the scope of my loop and 'this', but I can't really see what to change;
var stage;
var items = {
head: {image: null, path: "images/avatar-elements/head01.png", w:200, h:200},
hair: {image: null, path: "images/avatar-elements/hair01.png", w:200, h:200},
nose: {image: null, path: "images/avatar-elements/nose01.png", w:200, h:200},
eyes: {image: null, path: "images/avatar-elements/eyes01.png", w:200, h:200},
eyebrows: {image: null, path: "images/avatar-elements/eyebrows01.png", w:200, h:200},
ears: {image: null, path: "images/avatar-elements/ears01.png", w:200, h:200},
background: {image: null, path: "images/avatar-elements/background01.png", w:500, h:370}
};
function initCanvas() {
stage = new Kinetic.Stage("canvas", 500, 370);
makeBasis();
}
function makeBasis() {
for(i in items) {
var img = new Image();
img.onload = function() {
items[i].image = makeCanvasImage(this, items[i].w, items[i].h);
}
img.src = items[i].path;
}
}
function makeCanvasImage(tar, w, h) {
var theImage = new Kinetic.Image({
imageObj: tar,
x: 250 - (w / 2),
y: 185 - (h / 2),
width: w,
height: h
});
stage.add(theImage);
return theImage;
}
initCanvas();
推荐答案
错误在makeBasis()中。循环所有图像后,我设置为最后 - 经典闭包问题。尝试使用这个:
Bug is in makeBasis(). After looping on all images i is set to last - classic closure problem. Try to use this:
function makeBasis() {
for(i in items) {
var img = new Image();
img.onload = (function (nr) {
return function() {
items[nr].image = makeCanvasImage(this, items[nr].w, items[nr].h);
}
}(i));
img.src = items[i].path;
}
}
这篇关于Image.onload()的JavaScript循环/范围问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!