Matthew Jones

We're nearing the end of our Drawing with FabricJS and TypeScript series. In this part, let's add one last set of improvements by implementing cut, copy, and paste functionality as well as hotkey shortcuts for those, plus undo and redo.

We need to fill in each of the methods (other than the constructor, which for this class doesn't have an implementation; it just gets an instance of DrawingEditor).

Let's start with copy(). When we copy an object, we place a copy of it in memory so that it can be pasted later. In this particular case, we need to get the active object on the FabricJS canvas, clone it, and then set it to the memorizedObject property of Copier. Plus, we have an optional callback method that needs to be executed, if it is not undefined. Here's how that looks:

The callback method becomes immediately useful, because we now need to implement the cut() method. Cut is really just copy and then delete, so our cut() method will pass a function that deletes the selected object after it is cut. Here's the implementation:

cut() {
this.copy(() => this.editor.deleteSelected());
}

The last part of this is the paste() method. In this method, we clone the memorized object, add it to the canvas, and re-render the canvas. Here's the code:

But wait! There's currently no way the user can actually use this functionality! For cut/copy/paste, we aren't going to add display components to the toolbar. Instead, we're going to enable hotkeys (e.g. Ctrl+X, Ctrl+C, Ctrl+V).

Hotkeys

Not only will we enable hotkeys for cut, copy, and paste, we'll also enable them for undo (Ctrl+Z) and redo (Ctrl+Y). To start, we need our DrawingEditor class to be aware of the key codes for each of the letters. One of the ways we can do this is by using a very neat site called keycode.info. Here's the keycodes for X, C, V, Z, and Y:

TypeScript defines for us a KeyboardEvent class which represents an event where the user pressed a key on the keyboard. That event also tells us if the Ctrl key was pressed during the event. We can use this class to initialize our key code events:

That's all we need to do for hotkeys! Now the user can cut, copy, paste, undo, and redo using the keyboard shortcuts for those events! This is difficult to put into a GIF (because you wouldn't be able to see what keyboard shortcut I was using), so there won't be one for this part of the series.