How to set Image objects properties from options using FabricJS?


In this tutorial, we are going to learn how to set Image objects properties from options using FabricJS. We can create an Image object by creating an instance of fabric.Image. Since it is one of the basic elements of FabricJS, we can also easily customize it by applying properties like angle, opacity etc. In order to set Image objects properties from options, we use the setOptions method.

Syntax

setOptions(options: Object)

Parameters

  • options (optional) − This parameter is an Object which provides additional customizations to our object. Using this parameter origin, stroke width and a lot of other properties can be changed related to the image object.

Default appearance of image object

Example

Let’s see a code example to see how the Image object appears when the setOptions method is not used.

<!DOCTYPE html> <html> <head> <!-- Adding the Fabric JS Library--> <script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/510/fabric.min.js"></script> </head> <body> <h2>Default appearance of image object</h2> <p>You can see the default appearance of Image object</p> <canvas id="canvas"></canvas> <img src="https://www.tutorialspoint.com/images/logo.png" id="img1" style="display: none" /> <script> // Initiate a canvas instance var canvas = new fabric.Canvas("canvas"); canvas.setWidth(document.body.scrollWidth); canvas.setHeight(250); // Initiating the image element var imageElement = document.getElementById("img1"); // Initiate an Image object var image = new fabric.Image(imageElement); // Add it to the canvas canvas.add(image); </script> </body> </html>

Using setOptions method

Example

In this example, we have used the setOptions method to set the image properties from options. Here, we have applied a 4px stroke of colour “green” and re-adjusted the position of the Image object to the top value of 30 and a left value of 100.

<!DOCTYPE html> <html> <head> <!-- Adding the Fabric JS Library--> <script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/510/fabric.min.js"></script> </head> <body> <h2>Using setOptions method</h2> <p> You can see that the object's properties have been set using setOptions method </p> <canvas id="canvas"></canvas> <img src="https://www.tutorialspoint.com/images/logo.png" id="img1" style="display: none" /> <script> // Initiate a canvas instance var canvas = new fabric.Canvas("canvas"); canvas.setWidth(document.body.scrollWidth); canvas.setHeight(250); // Initiating the image element var imageElement = document.getElementById("img1"); // Initiate an Image object var image = new fabric.Image(imageElement); // Using setOptions method image.setOptions({ left: 100, top: 30, stroke: "green", strokeWidth: 4, }); // Add it to the canvas canvas.add(image); </script> </body> </html>

Updated on: 28-Oct-2022

562 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements