Image.onload()的JavaScript循环/范围问题

时间:2012-01-05 10:35:02

标签: javascript image loops scope

我正在尝试使用JavaScript循环一个对象,并将该对象的所有子对象添加到HTML5画布。

画布位工作正常,没有问题,但由于某些原因,我的所有图像最终都是相同的大小 - 最后一个子对象'背景'的大小。我假设它与我的循环范围和'this'有关,但我真的不知道要改变什么;

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

1 个答案:

答案 0 :(得分:11)

Bug在makeBasis()中。循环所有图像后,我被设置为最后 - 经典闭包问题。试着用这个:

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