在循环遍历通过loadFromJSON()加载的对象时,使用fabric.util.loadImage()的奇怪行为

时间:2015-03-03 11:31:11

标签: json fabricjs

为了尝试解决使用CORS(here)的奇怪问题,我试图重新加载通过 canvas.loadFromJSON()

加载的任何图像

但是,我遇到了奇怪的问题。有时只更换一个图像,有时我会复制一个图像。

这是我的代码:

canvas.loadFromJSON(<?php echo json_encode($objects); ?>, function() {
  var objArray = canvas.getObjects();

  for (var i = 0; i < objArray.length; i++) {
      canvas.setActiveObject(objArray[i]);

      var activeObject = canvas.getActiveObject();

      if(activeObject.type === 'image') {

          fabric.util.loadImage(activeObject.src, function(img) {
              var object = new fabric.Image(img);

              object.hasControls = true;
              object.lockUniScaling = true;
              object.scaleX = activeObject.scaleX;       
              object.scaleY = activeObject.scaleY;
              object.originX = activeObject.originX;
              object.originY = activeObject.originY;                
              object.centeredRotation = true;
              object.centeredScaling = true;

              canvas.add(object);
          }, null, {crossOrigin: 'Anonymous'});

          canvas.remove(activeObject);
      }
      activeObject.setCoords();
  }

  canvas.deactivateAll();
  canvas.renderAll();
  canvas.calcOffset();
});

为什么我会遇到这些奇怪的问题?

2 个答案:

答案 0 :(得分:0)

乍一看你的代码我没有看到任何错误...但我也认为代码可能有点低效?是否需要创建新的图像实例?

我相信你应该能够在图像对象上设置crossOrigin属性。

此代码未经测试,但我尝试这样的事情:

canvas.loadFromJSON(<?php echo json_encode($objects); ?>, function() {
  var objArray = canvas.getObjects();
  for (var i = 0; i < objArray.length; i++) {
    canvas.setActiveObject(objArray[i]);
    var activeObject = canvas.getActiveObject();
    if(activeObject.type === 'image') {
      activeObject.crossOrigin = 'Anonymous';
    }
  }
  canvas.deactivateAll();
  canvas.renderAll();
  canvas.calcOffset();
});

答案 1 :(得分:0)

我遇到了同样的问题,并且克服了这个问题,再次使用object._element创建了每个结构对象后,再次下载了图像,然后将其重新分配给loadFromJSON

export const getImage = url => {
  return new Promise((resolve, reject) => {
      let img = new Image();
      img.onload = () => resolve(img);
      img.onerror = reject;
      img.setAttribute('crossOrigin', 'anonymous');
      img.src = url;
  });
}
canvas.loadFromJSON(json, canvas.renderAll.bind(canvas), async (o, object) => {
  if (object.type === "image") {
    let imagecore = await getImage(object.src);
    object._element = imagecore;
  }
});