Layering canvas objects in Fabric.js

前端 未结 3 1758
再見小時候
再見小時候 2021-01-30 14:25

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 r

3条回答
  •  盖世英雄少女心
    2021-01-30 15:15

    If you want to set a specific ordering for all objects, instead of moving one object forward/backward, iterative calls to bring/send to front/back are slow.

    You can use the code of bringToFront as inspiration to speed this use case up: https://github.com/kangax/fabric.js/blob/586e61dd282b22c1d50e15c0361875707e526fd8/src/static_canvas.class.js#L1468

    And do this:

    fabric.Canvas.prototype.orderObjects = function(compare) {
        this._objects.sort(compare);
        this.renderAll();
    }
    

    Where compare defines the sorting, like:

    function compare(x,y) {
        return x.getWidth() * x.getHeight() < y.getWidth() * y.getHeight();
    }
    
    some_canvas.orderObjects(compare)
    

    If you wish to bring smaller objects to the front.

提交回复
热议问题