Images in a loop with FabricJS

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?

Answers:

Answer

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

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.