Add Keyboard Shortcuts to Undo & Redo Functionality with Fabric.JS Canvas
New here? Learn about Bountify and follow @bountify to get notified of new bounties! x

In my small app (kudos Wuddrum for OG answer which led to this) I am able to Undo and Redo changes to a canvas. I'd like to add keyboard shortcuts, for example CMD+Z to Undo and CMD+Shift+Z to Redo. I'm open to what simpler shortcuts you may think of.

Here is the JSFiddle: https://jsfiddle.net/Wuddrum/tv29xfkg/

Please have the functionality work with the JSFiddle. Let me know if I can provide more info that'll lead to a solution. Thank you.

awarded to GabLeRoux

Crowdsource coding tasks.

1 Solution

Winning solution

  1. Extract undo and redo into their own functions for reusability
  2. Add jquery code to catch (ctrl or cmd) + z and (ctrl or cmd) + shift + z and call undo or redo accordingly

Here's the diff

--- a/app.js
+++ b/app.js
@@ -442,7 +442,7 @@ $(function() {
         setAccent('https://images.unsplash.com/photo-1521158611-6b569322677d?ixlib=rb-0.3.5&ixid=eyJhcHBfaWQiOjEyMDd9&s=12bfcbf03e57cc99472bfb4f99541487&auto=format&fit=crop&w=250&q=60');
     });

-    $('#undo').click(function() {
+    function undo() {
         if(mainCanvas.mementoConfig.undoFinishedStatus){
             if(mainCanvas.mementoConfig.currentStateIndex === -1){
                 mainCanvas.mementoConfig.undoStatus = false;
@@ -471,9 +471,9 @@ $(function() {
                 }
             }
         }
-    });
+    }

-    $('#redo').click(function() {
+    function redo() {
         if(mainCanvas.mementoConfig.redoFinishedStatus){
             if((mainCanvas.mementoConfig.currentStateIndex === mainCanvas.mementoConfig.canvasState.length-1) && mainCanvas.mementoConfig.currentStateIndex != -1){
                 $('#redo').prop('disabled', true);
@@ -494,6 +494,18 @@ $(function() {
                 }
             }
         }
+    }
+
+    $('#undo').click(undo);
+    $('#redo').click(redo);
+
+    $(document).keydown(function (e) {
+        if (e.which === 90 && (e.ctrlKey || e.metaKey) && e.shiftKey) {
+            redo();
+        }
+        else if (e.which === 90 && (e.ctrlKey || e.metaKey)) {
+            undo();
+        }
     });

 });

Confirmed working here:

https://jsfiddle.net/gableroux/tv29xfkg/10/

Have a good day

Looks great, thanks!
sharper 30 days ago