Adding a pattern with image and colour to a Polygon using FabricJS


We can create a Polygon object by creating an instance of fabric.Polygon. A polygon object can be characterized by any closed shape consisting of a set of connected straight line segments. 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 add pattern with image and colour to a Polygon, we can use the Pattern class in FabricJS.

Syntax

new fabric.Pattern( options: Object, callback: function )

Parameters

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

  • callback − This parameter is a function which is invoked after callback initialization. This parameter is optional.

Example 1: Creating an instance of fabric.Pattern() and adding it to our Polygon object

Let’s see a code example to see how we can create an instance of fabric.Pattern and add it to the canvas. Here, we have created a polygon object which is in the shape of a rectangle (an irregular polygon). We have initialized the createPattern function which will add the pattern to our rectangle. Finally we have called the createPattern function and passed it the desired URL.

<!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>
      Creating an instance of fabric.Pattern() and adding it to our Polygon object
   </h2>
   <p>You can see that a pattern has been created</p>
   <canvas id="canvas"></canvas>
   <script>
      
      // Initiate a canvas instance
      var canvas = new fabric.Canvas("canvas");
      canvas.setWidth(document.body.scrollWidth);
      canvas.setHeight(250);
      
      // Initiating the createPattern function which loads image

      // and adds the image as pattern to the rect object
      function createPattern(url) {
         fabric.util.loadImage(url, function (img) {
            rect.set(
               "fill",
               new fabric.Pattern({
                  source: img,
               })
            );
            canvas.renderAll();
         });
      }
      
      // Initiating a Polygon object
      var rect = new fabric.Polygon(
         [
            { x: 0, y: 0 },
            { x: 500, y: 0 },
            { x: 500, y: 200 },
            { x: 0, y: 200 },
         ],
         {
            left: 50, 
            top: 20,
            stroke: "black",
         }
      );
      
      // Adding it to the canvas
      canvas.add(rect);

      // Calling the createPattern function
      createPattern("https://www.tutorialspoint.com/images/logo.png");
   </script>
</body>
</html>

Example 2: Adding a pattern with Image and Colour to our Polygon

Let’s see a code example to see how we can create a dynamic pattern with image and colour to our Polygon object. In this case, we have used the fromURL method to load the image and also initialized an object of fabric.StaticCanvas(), one of FabricJS’s main rendering surfaces, which is crucial for creating dynamic patterns.

We have used setBackgroundColor method to set the background colour for the polygon. Finally, we have added the polygon object to the canvas.

<!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>Adding a pattern with Image and Colour to our Polygon</h2>
   <p>You can see that a pattern with image and colour has been created and further use the number field to change the pattern density</p>
   <label>Add a width value(50-500): </label>
   <input type="number" id="changeWidth" value="50"/>
   <canvas id="canvas"></canvas>
   <script>
      
      // Initiate a canvas instance
      var canvas = new fabric.Canvas("canvas");
      canvas.setWidth(document.body.scrollWidth);
      canvas.setHeight(250);
      
      // Initiating the colour that we want to fill the pattern with
      var imgColor = "rgba(216,228,188,0.5)";
 
      // Using fromURL method to load image and add to canvas
 
      // further setting the dimensions and background colour
      fabric.Image.fromURL(
         "https://www.tutorialspoint.com/images/logo.png",
         function (img) {
            img.scaleToWidth(100);
            img.scaleToHeight(90);
            var patternSourceCanvas = new fabric.StaticCanvas();
            patternSourceCanvas.add(img);
            patternSourceCanvas.renderAll();
            patternSourceCanvas.setBackgroundColor(
               imgColor,
               patternSourceCanvas.renderAll.bind(patternSourceCanvas)
            );
            
            // Initiating a Pattern object
            var pattern = new fabric.Pattern({
               source: patternSourceCanvas.getElement(),
               repeat: "repeat",
            });
            
            // Adding a polygon object to the canvas
            canvas.add(
               
               // Initiate a polygon object
               new fabric.Polygon(
                  [
                     { x: -100, y: -175 },
                     { x: 100, y: -175 },
                     { x: 200, y: 0 },
                     { x: 100, y: 175 },
                     { x: -100, y: 175 },
                     { x: -200, y: 0 },
                  ],
                  {
                     top: 30,
                     left: 10,
                     strokeWidth: 3,
                     stroke: "#96c8a2",
                     fill: pattern,
                     objectCaching: false,
                     scaleX: 0.5,
                     scaleY: 0.5,
                  }
               )
            );
            
            // Using getElementById and targeting the input tag with the id as "changeWidth"
            document.getElementById("changeWidth").oninput = function () {
               img.scaleToWidth(parseInt(this.value, 10));
               patternSourceCanvas.setDimensions({
                  width: img.getScaledWidth(),
                  height: img.getScaledHeight(),
               });
               canvas.requestRenderAll();
            };
         }
      );
   </script>
 </body>
</html> 

Conclusion

In this tutorial, we used two simple examples to demonstrate how you can add a pattern with image and colour to a Polygon using FabricJS.

Updated on: 28-Dec-2022

741 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements