Skip to content
Related Articles

Related Articles

Improve Article

How to create a canvas image using Fabric.js ?

  • Last Updated : 19 May, 2020
Geek Week

In this article, we are going to see how to create a canvas-like image in JavaScript. Thee canvas like image means the image is movable and can be resized according to requirement.

Approach: To make this possible we are going to use a JavaScript library called FabricJS. After importing the library, we will create a canvas block in the body tag which will contain our image. Further, we will create an img element which contains the image to be added inside the canvas and set the style attribute to display:none; because we don’t want the image to be visible outside the canvas. After this, we will initialize instances of Canvas and Image provided by FabricJS and render the Image on the Canvas as given in the example below.

Syntax:

 fabric.Image( image_element ); 

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




<!DOCTYPE html>
<html>
  
<head>
    <title>
        How to create a canvas-type
        image with JavaScript?
    </title>
  
    <!-- Loading the FabricJS library -->
    <script src=
    </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=
                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:

Hey geek! The constant emerging technologies in the world of web development always keeps the excitement for this subject through the roof. But before you tackle the big projects, we suggest you start by learning the basics. Kickstart your web development journey by learning JS concepts with our JavaScript Course. Now at it’s lowest price ever!




My Personal Notes arrow_drop_up
Recommended Articles
Page :