Images in a loop with FabricJS

随声附和 提交于 2019-12-01 10:43:33

问题


I am using fabricjs and I have a JSON list of images. each element represents an image with info such as left, top etc for each image. in my javascript code I have the following

    for (var j = 0; j < ChrImages.d.length; j++) {

    var obj = ChrImages.d[j];

    fabric.util.loadImage(obj.URL, function (img) {
        var customImage = new fabric.CustomImage(img, { name: obj.Name, rot: obj.Rotation, rawURL: obj.RawURL, belongsto: obj.BelongsTo,left:obj.PosX,top:obj.PosY,angle:obj.Rotation });
        //customImage.set({
        //    left: obj.PosX,
        //    top: obj.PosY,
        //    angle: obj.Rotation,
        //    lockScalingX: true,
        //    lockScalingY: true,
        //    perPixelTargetFind: true,
        //});
     //   customImage.filters.push(new fabric.Image.filters.RemoveWhite());
        canvas.add(customImage);
        groupWorkingChromosomeImages.add(customImage);
    });

    }

the issue I am having is that all the images are stacked over one another. it seems all images get the same left and top.

I have check to make sure that the JSON list is accurate. Also, I need to use a custom class as my images have additional attributes.

Can someone please let me know why adding images in the tight loop is failing?


回答1:


Your variable obj is not in the same scope of the loadImage function, so this gives you unexpected results cause you can't control when loadImage fires. Probably it fires much after your for loop finishes.

use this code and tell me if it helped:

for (var j = 0; j < ChrImages.d.length; j++) {
    var currentObj = ChrImages.d[j];

    //closure, create a scope for specific variables
    (function (obj) {
        fabric.util.loadImage(obj.URL, function (img) {
            var customImage = new fabric.CustomImage(img, {
                name: obj.Name,
                rot: obj.Rotation,
                rawURL: obj.RawURL,
                belongsto: obj.BelongsTo,
                left: obj.PosX,
                top: obj.PosY,
                angle: obj.Rotation
            });
            canvas.add(customImage);
            groupWorkingChromosomeImages.add(customImage);
        });

    })(currentObj);

}

i wrapped your loadImage function so it will use the right obj instance inside closure, tell me if it works.

cheers



来源:https://stackoverflow.com/questions/17442299/images-in-a-loop-with-fabricjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!