有没有一种通过官方API在Fabric.js画布上分层对象的方法?目前我发现唯一的方法是手动迭代canvas._objects并重新排序,以便按特定顺序进行绘制。是否有更好的方法来做到这一点,而不会(可能)破坏对象?
有没有一种通过官方API在Fabric.js画布上分层对象的方法?目前我发现唯一的方法是手动迭代canvas._objects并重新排序,以便按特定顺序进行绘制。是否有更好的方法来做到这一点,而不会(可能)破坏对象?
[编辑] 我已经更正了以下信息(我的错,我最初想到的是KineticJs api)。
FabricJS有这些API方法可以改变对象的z-index:
canvas.sendBackwards(myObject)
canvas.sendToBack(myObject)
canvas.bringForward(myObject)
canvas.bringToFront(myObject)
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();
},
这是我的做法。我为每个织物对象添加了一个zIndex属性,并在它们添加到画布后调用了一个排序函数:
const CIRCLE_INDEX = 1
let object = new fabric.Circle({
left: 10,
top: 10,
radius: 5
...other properties
zIndex: CIRCLE_INDEX
});
在添加了您的对象之后,调用以下函数:
const sortObjects = () => {
canvas._objects.sort((a, b) => (a.zIndex > b.zIndex) ? 1 : -1);
canvas.renderAll();
}
fabric.Canvas.prototype.orderObjects = function(compare) {
this._objects.sort(compare);
this.renderAll();
}
在排序时,可以使用 compare 定义排序规则,例如:
function compare(x,y) {
return x.getWidth() * x.getHeight() < y.getWidth() * y.getHeight();
}
some_canvas.orderObjects(compare)