问题描述
是否可以通过官方API在Fabric.js画布上分层对象?现在,我发现做到这一点的唯一方法是手动遍历canvas._objects并对它们重新排序,以便按特定顺序绘制它们.有没有更好的方法可以做到(可能)不会破坏对象?
Is there a way to layer objects on a Fabric.js canvas via the official API? Right now the only way I have found to do it is to manually iterate through the canvas._objects and reorder them so that they get drawn in a specific order. Is there a better way to do this that doesn't (potentially) break the object?
推荐答案
我已经更正了以下信息(不好,我原本是在考虑KineticJs api).
I've corrected my info below (my bad, I was originally thinking of the KineticJs api).
FabricJS具有以下API方法,这些方法会更改对象的z-index:
FabricJS has these API methods that change the z-index of objects:
canvas.sendBackwards(myObject)
canvas.sendToBack(myObject)
canvas.bringForward(myObject)
canvas.bringToFront(myObject)
在幕后,FabricJs通过从getObjects()数组中删除对象并将其拼接回所需位置来更改z-index.它具有很好的优化功能,可以检查相交的对象.
Under the covers, FabricJs changes the z-index by removing the object from the getObjects() array and splicing it back in the desired position. It has a nice optimization that checks for intersecting objects.
bringForward: function (object) {
var objects = this.getObjects(),
idx = objects.indexOf(object),
nextIntersectingIdx = idx;
// if object is not on top of stack (last item in an array)
if (idx !== objects.length-1) {
// traverse up the stack looking for the nearest intersecting object
for (var i = idx + 1, l = this._objects.length; i < l; ++i) {
var isIntersecting = object.intersectsWithObject(objects[i]) ||
object.isContainedWithinObject(this._objects[i]) ||
this._objects[i].isContainedWithinObject(object);
if (isIntersecting) {
nextIntersectingIdx = i;
break;
}
}
removeFromArray(objects, object);
objects.splice(nextIntersectingIdx, 0, object);
}
this.renderAll();
},
这篇关于在Fabric.js中分层画布对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!