Fabric.js Tutorial – Part 2: Add Object to Canvas

Fabric.js Tutorial – Part 2: Add Object to Canvas


In previous video, we’ve created a rectangle shape object For this video, we’re going to go over the detail step by step of how it works First of all, we need a canvas and initialize it with Fabric.js Next, you can create an object to add into the canvas Each object has its own properties such as top, left, width and height You can override the default value here. For example, I’ll set “angle” to rotate it 45 degrees or other properties such as opacity Some properties are unique for each object type. For example, “radius” is unique for “Circle” object To see all the properties of each object type, please refer to the Fabric.js documentation page Another interesting property is “selectable” You can set it to false if you don’t want users able to to select the canvas object (So they can’t scale or mess up the canvas) Next, we’ll talk about Methods Each object has their own useful methods. You’ll need them if you want to manipulate the canvas via javascript For example, if you want to get a “Top” position, you’ll need to call getTop() Or if there are multiple objects overlapped in the canvas, you can call bringToFront() to get that object to the front I’m going to show you how to move our rectangle object programatically when user click the button We’ll use setLeft() to change the “Left” property Then we’ll get the current Left by calling getLeft() and add another 10px After you’ve done with the update, we’ll need to re-render the canvas by calling renderAll() method The object properties can also be updated by using manual transform I’m going to add a script to display “Top”, “Left” and “Angle” to the console You’ll see that these are the initial properties that we set Now, I’ll try to manually tranform it a bit You’ll see that all the properties are now reflecting the new values immediately. Again, you can see all available methods for each object type at the Fabric.js Documentation In the next video, we’ll learn how to add image to the canvas Thanks for wathcing! Like or subscribe if this video is helpful 🙂

2 Replies to “Fabric.js Tutorial – Part 2: Add Object to Canvas”

Leave a Reply

Your email address will not be published. Required fields are marked *