search
HomeWeb Front-endJS TutorialAdd patterns with images and colors to polygons using FabricJS

Add patterns with images and colors to polygons using FabricJS

We can create a polygon object by creating an instance of fabric.Polygon. A polygonal object can be described 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 patterns and colors to polygons, we can use the Pattern class in FabricJS.

Grammar

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

parameter

  • 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 called after the callback is initialized. This parameter is optional.

Example 1: Create an instance of fabric.Pattern() and add it to our polygon object

Let's look at a code example to see how to create an instance of fabric.Pattern and add it to the canvas. Here, we create a polygon object whose shape is a rectangle (an irregular polygon). We initialize the createPattern function which will add the pattern to our rectangle. Finally, we call the createPattern function and pass it the required 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 of images and colors to our polygons

Let's look at a code example to see how to create a dynamic pattern with an image and color for our polygon object. In this case, we used the fromURL method to load the image and initialized a fabric.StaticCanvas() object, which is one of the main rendering surfaces of FabricJS and is useful for creating Dynamic patterns are crucial.

We used the setBackgroundColor method to set the background color for the polygon. Finally, we add 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 id="Adding-a-pattern-with-Image-and-Colour-to-our-Polygon">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> 

in conclusion

In this tutorial, we use two simple examples to demonstrate how to use FabricJS to add images and patterns of color to polygons.

The above is the detailed content of Add patterns with images and colors to polygons using FabricJS. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:tutorialspoint. If there is any infringement, please contact admin@php.cn delete
From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools