使用FabricJS循环中的图像 [英] Images in a loop with FabricJS

查看:210
本文介绍了使用FabricJS循环中的图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用fabricjs,我有一个JSON图像列表。每个元素代表一个图像,其中包含每个图像的左,上等信息。在我的javascript代码中,我有以下

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.

我已经检查以确保JSON列表是准确的。此外,我需要使用自定义类,因为我的图像具有其他属性。

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?

推荐答案

您的变量 obj 与loadImage函数的范围不同,因此这会给您带来意想不到的结果你无法控制loadImage何时触发。在您的 for 循环结束后,它可能会激发很多。

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

}

我包装了你的loadImage函数,所以它将使用正确的obj关闭内部的实例,告诉我它是否有效。

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

欢呼

这篇关于使用FabricJS循环中的图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆