Can you help me figure out what is going on here.
Basically I want to use FabricJS with ReactJS and Redux. I want to store the currently selected objects in redux store. But it seems it has a weird behavior when it comes to saving the active objects of multi selection.
let selectedObjects = null;
let canvas = new fabric.Canvas('canvas-area', {
preserveObjectStacking: true,
width: 500,
height: 500
});
canvas.add(new fabric.Rect({
left: 100,
top: 100,
fill: 'blue',
width: 100,
height: 100
}));
canvas.add(new fabric.Circle({
radius: 50,
fill: 'green',
left: 200,
top: 200
}));
canvas.renderAll();
// =======================
document.querySelector('#save-selection').addEventListener('click', ()=> {
//selectedObjects = Object.assign({}, canvas.getActiveObject());
selectedObjects = canvas.getActiveObject();
canvas.discardActiveObject();
canvas.renderAll();
});
document.querySelector('#apply-saved-selection').addEventListener('click', ()=> {
canvas.setActiveObject(selectedObjects);
canvas.renderAll();
});
<html>
<body>
<button id='save-selection'>Save Selection</button>
<button id='apply-saved-selection'>Apply Saved Selection</button>
<canvas id='canvas-area'></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/2.3.3/fabric.min.js"></script>
</body>
</html>
Basically the way you use the code snippet above are:
Use Case 1 : Single selected object
- Select a single object.
- Click Save Selection ( it will save the current selected object and clear current canvas selection ).
- Click Apply Saved Selection.
- Drag the currently selected object, the selection and the selected object stays in synced and the app works as expected.
Use Case 2 : Multiple selection
- Select multiple objects.
- Click Save Selection.
- Click Apply Saved Selection.
- Drag the currently selected objects, as you can see, only the selection is dragged, the actual selected objects are left behind (unsynced).
Can you help me figure out how to properly saved the selected object/s for later use?
Thanks in advance
Note: I'm using latest FabricJS (2.3.3)