Open In App

How to create a canvas image using Fabric.js ?

Last Updated : 24 Jun, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Creating a canvas image using Fabric.js is a powerful method for generating dynamic and interactive graphical content on the web. Fabric.js, a robust JavaScript library, simplifies the process of working with the HTML5 canvas element by providing a rich API for manipulating shapes, text, and images. With Fabric.js, developers can easily create, transform, and animate graphical elements, making it an ideal tool for building complex visualizations, interactive graphics, and responsive web applications. This article will guide you through the steps to create a canvas image using Fabric.js, illustrating its versatility and ease of use.

Approach to creating a canvas image

  • Load the Fabric.js Library: Include the Fabric.js library in your HTML file to gain access to its features.
  • Create a Canvas Element: Define a canvas element in your HTML where the image will be displayed.
  • Add an Image Element: Include the image you want to use, but keep it hidden as it will only be needed within the canvas.
  • Initialize Fabric.js Canvas: Create a Fabric.js canvas instance using the specified HTML canvas element.
  • Load and Add the Image: Retrieve the hidden image element, initialize it as a Fabric.js image object, and add it to the canvas

Syntax:

 fabric.Image( image_element ); 

Example: This example uses FabricJS to create a simple editable canvas image. 

html
<!DOCTYPE html>
<html>

<head>
    <title>
        How to create a canvas-type
        image with JavaScript?
    </title>

    <!-- Loading the FabricJS library -->
    <script src=
"https://cdnjs.cloudflare.com/ajax/libs/fabric.js/3.6.2/fabric.min.js">
    </script>
</head>

<body>
    <canvas id="canvas" width="600" height="200"
        style="border:1px solid #000000">
    </canvas>

    <!-- Add the image to be used in the canvas
        and hide it here because only need it
        inside the canvas -->
    <img style="display: none;" src=
"https://media.geeksforgeeks.org/wp-content/uploads/20200327230544/g4gicon.png"
                id="my-image" alt="">
                
    <script>
        // Initiate a Canvas instance
        var canvas = new fabric.Canvas("canvas");

        // Get the image element
        var image = document.getElementById('my-image');

        // Initiate a Fabric instance
        var fabricImage = new fabric.Image(image);

        // Add the image to canvas
        canvas.add(fabricImage);
    </script>
</body>

</html>

Output:



Next Article

Similar Reads