我正在使用 fabricjs 并且我有一个 JSON 图像列表。每个元素代表一个图像,其中包含每个图像的左、上等信息。在我的 javascript 代码中,我有以下内容
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);
});
}
我遇到的问题是所有图像都堆叠在一起。似乎所有图像的左侧和顶部都相同。
我已检查以确保 JSON 列表准确无误。此外,我需要使用自定义类,因为我的图像具有其他属性。
有人可以告诉我为什么在紧密循环中添加图像失败吗?
最佳答案
您的变量 obj 与 loadImage 函数不在同一范围内,因此这会给您带来意想不到的结果,因为您无法控制 loadImage 何时触发。可能它会在您的 for 循环结束后多次触发。
使用此代码并告诉我它是否有帮助:
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 实例,告诉我它是否有效。
干杯
关于javascript - 使用 FabricJS 循环图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17442299/