Fabric.js History Operations (undo, redo) and Useful Tips

History

First of all, most required features are undo and redo actions. In fabric.js almost every action is catched with object:modified, object:added and object:removed. Basically, we are keeping the state of the canvas on a stack and redraw the state each time.

npm package

I have created a npm package in order to make it easier to apply the processes we discussed above. Additionally, it includes redo action. You can install the package using with

npm install fabric-history
import 'fabric-history';
const canvas = new fabric.Canvas('canvas');
canvas.historyInit();
canvas.undo();
canvas.redo();

Download the canvas with higher resolution

Second problem I have faced, my canvas had lower resolution than I needed, and I wanted to download the high resolution version of it. There is a built-in solution for this. Basically, you can multiply the canvas while downloading by

canvas.toDataUrl({ multiplier: 3 });

Clip canvas

In most cases, I wanted to clip objects with different kind of shapes. HTML5 canvas has a property called globalCompositeOperation.

https://www.rgraph.net/canvas/reference/globalcompositeoperation.html

Conclusion

In this blog post, we learned how to use globalCompositeOperation with fabric.js’s objects. Additionally, I have published my first npm package under name fabric-history.

UPDATE

I have updated the fabric-history package. historyInitfunction is not necessary anymore. You just import the package and use undo , redo functions.

Resources

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store