Intro to Fabric.js
Today we will be looking at a fun library I have been working with recently called Fabric.js. Fabric provides us with an interactive object model that is on top of the native canvas element. It allows us to easily add objects to the canvas and manipulate them in various ways. Let’s check it out. I am working on a React project currently, so we will be working with fabric in React. First things first let’s head to our terminal and create our project. (Also this may only be helpful if you are familiar with React, as well as React Hooks)
npx create-react-app fabric-test
Now lets install the fabric package
npm install fabric — save
Now lets npm start and get started. Head to the App.js file in your src folder. We can go ahead and delete everything inside our return function, just leave an empty <div></div> for now.
In order to use fabric we will need to import it at the top of our page, as well we are going to need to import useState and useEffect from react.
To get working with fabric we must create a canvas element and then we can create the fabric canvas that servers as a wrapper around the <canvas> element. This fabric canvas is responsible for managing all of the fabric objects on that particularly canvas.
Create a canvas with an id of ‘canvas’. Then create a state variable for our fabric canvas, to save and access. We will then create a useEffect function that will run when our App component loads.
We can create a new fabric canvas with new fabric.Canvas(‘…’). It takes an id of an element and returns an instance of the fabric.Canvas.
Now add renderFabricCanvas to your setCanvas function. You should see a large purple rectangle on your screen, that’s our fabric canvas, now let’s add some fabric objects!
We can easily add basic shapes like triangles, rectangles or circles by using new fabric.Rect(), fabric.Circle(), or fabric.Triangle(). We then can pass any attributes we would like right away or we can set the attributes after creating the object. I will use both examples.
Here is what you should see on your screen and also notice the console, there is the console.log of our canvas object. You can see there is a lot going on and we will cover more later, but for now just focus on the objects, see the (3), this represents the three shapes we have created. Our shapes are conveniently all located together in one objects array. Our fabric canvas element makes it easy to access and manipulate the various objects that are on our canvas.
Next time we will see how easy it is to access these objects and will take advantage of fabrics built in event listeners.
Here is the full code for above.