Control z-index in Fabric.js

廉价感情. 提交于 2019-12-03 10:52:15
Kienz

Since fabric.js version 1.1.4 a new method for zIndex manipulation is available:

canvas.moveTo(object, index);
object.moveTo(index);

I think this is helpful for your use case. I've updated your jsfiddle - i hope this is what you want:
jsfiddle

Also make sure you change z-index AFTER adding object to canvas.

So code will looks like:

canvas.add(object);
canvas.moveTo(object, index);

Otherwise fabricjs don`t care about z-indexes you setup.

You can modify your _chooseObjectsToRender method to have the following change at the end of it, and you'll be able to achieve css-style zIndexing.

objsToRender = objsToRender.sort(function(a, b) {
  var sortValue = 0, az = a.zIndex || 0, bz = b.zIndex || 0;

  if (az < bz) {
    sortValue = -1;
  }
  else if (az > bz) {
    sortValue = 1;
  }

  return sortValue;
});

https://github.com/fabricjs/fabric.js/pull/5088/files

After I added a line object, I was make the line appear under the object using:

canvas.add(line);
canvas.sendToBack(line);

Other options are

  • canvas.sendBackwards
  • canvas.sendToBack
  • canvas.bringForward
  • canvas.bringToFront

see: https://github.com/fabricjs/fabric.js/issues/135

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