fabricjs placement of images on canvas inconsistent

前提是你 提交于 2019-12-03 22:47:14

It looks like you have a race condition from the images loading in different orders.

The fabric.Image.fromURL() method is using a callback function, which fires after the image has loaded, so you're not guaranteed to have that inner function fire in the same order you called it. But you're using curObject to increment upwards each time the function is called, which assumes they're called in order. And the objRef can get re-assigned to a new object by the time the image loads, which would be why the x/y/rotate values are off (using the values from the other objects in the array).

So, instead of using img.set() after the image had loaded, use the third parameter of the Image.fromURL() method to pass in your attributes:

for (var i=0; i<objects.length;i++){
  var objRef = objects[i];
  switch(objRef.type){
    case 'image':
      var url = "img/" + objRef.filename;
      fabric.Image.fromURL(url, function(img) {
        canvas.add(img).renderAll();
      }, {
        left: objRef.x,
        top: objRef.y,
        angle: objRef.angle,
        hasBorders: false,
        hasControls: false,
        hasRotatingPoint: false,
        lockMovementX: true,
        lockMovementY: true
      });
      break;

    case 'text':
      // ...
      break;
  }
}

So the key to the answer is async call back. Just check when the Alert message called out.

fabric.Image.fromURL('hulk.png', function (img) {
    alert('came1');
    canvas.add(img).renderAll();
    }, {
        id: 'hulkid',
        num: 1,
        left: 10,
        top: 10,
        angle: 0
    });

fabric.Image.fromURL('hulk.png', function (img) {
    alert('came2');
    canvas.add(img).renderAll();
}, {
    id: 'hulkid',
    num: 2,
    left: 25,
    top: 25,
    angle: 0
});
alert('came Last');
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!