Hi I want to have Layers sort control like on photoshop using FabricJS
I have this solution but it’s not working well when you have more than 3 objects on canvas:
$("#containerLayers").sortable({
change: function(event, ui){
$( "#containerLayers li" ).each(function(index,list){
if(objectArray[$(list).attr('id')]){
canvas.moveTo(objectArray[$(list).attr('id')],index);
}
});
canvas.renderAll();
}
});
Here is other parts of code:
https://jsfiddle.net/peLcju2h/16/
does anyone have a better solution than this?
2
Answers
Best solution for Layer ordering using FabricJS is this one:
Instead of using
canvas.moveTo()
just usecanvas.sendToBack()
and it will work perfectHere is link and you can see that ordering is working good https://jsfiddle.net/peLcju2h/24/
First of all, you have some important refactorings to make in your code, mainly because of the fact that a lot of its snipets are duplicated.
I did it already, and the final working code is here: https://jsfiddle.net/peLcju2h/18/
Let’s see some considerations:
You were adding objs to your array through
push()
function, which is not wrong, but it messed up with your UI sortable handling. That’s because every time you changeli
‘s position, only the canvas and HTML are updated, but not the array itself.You could use a reordering function for this, but it wouldn’t fit the goal here once element positions don’t have a predefined order or changing logic.
Instead, I decided to go with an auxiliary array, which is gonna be populated every time the items are sorted.
Push the items via
[]
operator into the array, using the objectid
as the key;objectArray
will be rendered only after the canvas work has been done.