Undo / Redo with 2 Canvases in Fabric.JS
New here? Learn about Bountify and follow @bountify to get notified of new bounties! x

Undo / Redo Question

I have a small JSFiddle that allows me to undo and redo. I have a second fiddle that has 2 canvases (for a front and back) and I’ve been trying to incorporate the functionality from the first JSFiddle into it. Basically, in the second JSFiddle, I need to be able to toggle between the Front and Back and be able to Undo / Redo.

Here is the original Undo / Redo JSFiddle: https://jsfiddle.net/code4ever/zkqw7980/

And here is what I’ve been trying to incorporate it into: https://jsfiddle.net/code4ever/ejrcyq9s/

Please let me know if I can add more information to help you provide a solution. Thanks!

Using a stack of n canvases (in this case 2) is not a very efficient way to store previous states. You should serialize the fabric.js canvas as JSON each time you make a change and store a list of past states that way. Then you don't need to keep an extra canvas in the DOM.
slang800 7 months ago
I would go a step even further, and store only the differences (deltas) between each JSON history state using a library like this: http://json-delta.readthedocs.io/en/latest/javascript.html or https://github.com/benjamine/jsondiffpatch.
kostasx 7 months ago
Here's something I've quickly set up to test the JSON diff strategy: https://codepen.io/kostasx/pen/YjGrYB?editors=0011 Works only with text modification at the current moment.
kostasx 7 months ago
@slang800, thank you for that suggestion! @kostasx, and thank you for yours. I'm checking those out now, they look interesting!
sharper 7 months ago
awarded to Wuddrum

Crowdsource coding tasks.

1 Solution

Here's my solution: JSFiddle

It's based on the example you provided, but with some bugs fixed.

Undo/Redo supports all elements (BG/Text/Frame/Accents) and both (back and front) canvas. Canvas have their own separate undo states of course.

EDIT: Fixed a bug JSFiddle

This looks great. Mind if I pop back for follow up questions (for tips of course?). Thanks Wuddrum
sharper 7 months ago
I did notice one thing: When I add a background, and then an accent image, but then undo all changes and then select a frame, the old background reappears. Do you find that it does this for you too?
sharper 7 months ago
Didn't catch that one when I was testing, but yes, it's happening for me also. I'm looking into it.
And as always, I'll answer follow up questions.
Wuddrum 7 months ago
I've updated my solution with a fixed version. Everything seems to be working now.
Wuddrum 7 months ago
Hey, it's working for me too. Thank you!
sharper 7 months ago
Thank you for the tip!
Wuddrum 7 months ago
You are most welcome
sharper 7 months ago