Fabric.js - problem with drawing multiple images zindex

℡╲_俬逩灬. 提交于 2019-11-28 11:31:56

There are couple of issues here.

1) You can't change zindex of images by setting their zindex property. Fabric images simply don't have such property and changing it doesn't change z index of images on canvas. This makes all those .set('zindex', 0), .set('zindex', 1), etc. pretty much a no-op.

2) bringToFront works as expected here, bringing last image all the way to the top of the drawing stack. But the problem is that "images/player-board-top-red.png" image which you're loading last is not guaranteed to be the last one added. Those 4 requests are asynchronous; they are coming in any order, and so callbacks are executed in any order as well. In my test, for example, the last image comes second, callback executes, image is brought to the front, but is then "overwritten" by following 2 callbacks.

How to make last image render on top? Well, we can simply check that all images are loaded before attempting to bring last one to the top:

var img4;
// ...
function checkAllLoaded() {
  if (canvas.getObjects().length === 4) {
    canvas.bringToFront(img4);
  }
}
// ...
fabric.Image.fromURL('images/1.png', function(img) {
  img.set('left', 0).set('top', 0);
  canvas.add(img);
  checkAllLoaded(img);
});
// load other images, making sure to include `checkAllLoaded` in callback
fabric.Image.fromURL('images/4.png', function(img) {
  img4 = img.set('left', 0).set('top', 0);
  canvas.add(img);
  checkAllLoaded(img);
});

By the way, don't forget that you can pass an object to set method like so:

img.set({ left: ..., top: ... });

And since set is chainable and returns reference to an instance, you can even pass it to add like so:

canvas.add(img.set({ left: ..., top: ... }));

Hope this helps.

Amit Sharma

You can use canvas.insertAt(object,index); instead of canvas.add(object) to set object's zIndex as per your choice.

Also you can get any object by using:

canvas_object = canvas.item(index);

If you want to bring that object in front, use:

canvas_object.bringForward() 

//or

canvas_object.bringToFront() 
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!