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.

The Sample Project

Don’t forget about the sample project over on GitHub! It contains the final code for this entire series.

The Copier Class

Let’s start with the copier class, which will implement our cut, copy, and paste functionality. The skeleton of this class looks like this:

class Copier {
    //During cut or paste, memorizedObject is the object that 
    //will be held in memory and then pasted
    private memorizedObject: fabric.Object

    constructor(private readonly editor: DrawingEditor) { }

    copy(callBack?: Function) { }

    cut() { }

    paste() { }
}

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:

copy(callBack?: Function) {
    //Get active object on canvas
    const activeObject = this.editor.canvas.getActiveObject();

    //If the active object is not null
    if (activeObject !== null) {
        //Clone the object...
        activeObject.clone((object) => {
            //...and set it as the memorizedObject property
            this.memorizedObject = object;

            //When the object is pasted, offset the paste location
            //from the original object.
            object.set({
                left: object.left + 10,
                top: object.top + 10
            });

            //If the callback method exists, call it
            if (callBack !== undefined)
                callBack();
        });
    }
}

#fabricjs

Drawing with FabricJS and TypeScript : Cut/Copy/Paste and Hotkeys
1.30 GEEK