DEV Community

Cover image for Quotes Maker with Javascript using Fabric Js
Siddhartha
Siddhartha

Posted on

Quotes Maker with Javascript using Fabric Js

Fabric Js helps you easily create graphic editors.

You must know basic Javascript for this purpose.

It's easy.

Demo: https://codepen.io/isneuu/pen/XWgxLPv

Download

Download the Fabric Js's Javascript file from here.

https://cdn.jsdelivr.net/npm/fabric@4.6.0/dist/fabric.min.js

Or visit http://fabricjs.com/ for better instructions.

Our HTML

We will have simple features:

  • Add quote
  • Add author
  • Delete text
  • Download Image
<div class = "buttons">

  <button class = "button" type="button" onclick="addTextToCanvas('quote')">Add Quote</button>

  <button class = "button" type="button" onclick="addTextToCanvas('author')">Add Author</button>

  <a href="" class = "button" onclick = "convertToImage()" id='downloader'>Download</a>

  <button type="button" id='delete' name="button">delete text layer</button>

</div>
Enter fullscreen mode Exit fullscreen mode

Next we'll create the Canvas.

<canvas id="myCanvas" width="800" height="500" style="border:1px solid #000000; margin-top  : 30vh;  margin-left : 25%">
</canvas>
Enter fullscreen mode Exit fullscreen mode

You can see we created a canvas container with id myCanvas, width, height, and basic styling.

This is inline styling. Please feel free to create a class and style.

Import Fabric Js

<script src="fabric.js" charset="utf-8"></script>
Enter fullscreen mode Exit fullscreen mode

Writing our Javascript

 const canvas = new fabric.Canvas('myCanvas');
 canvas.backgroundColor = '#ffffff';

Enter fullscreen mode Exit fullscreen mode

It will create a canvas from the Canvas ID.

We've set the background color of canvas to white. If not mentioned, it will be transparent.

Adding a text element

textBox = new fabric.IText("My Text", {
          left : 70,
          top: 100});

canvas.add(textBox);

Enter fullscreen mode Exit fullscreen mode

First we created a text element that will appear on position top 100, left 70 from the Canvas.

Then we added that text element to the Canvas.

Easy, right?

Now let's add more controls.

    textBox = new fabric.IText("Andrea Dykstra", {
          left : 70,
          top: 350,
          fontFamily: 'Inter',
          fontWeight: 'Normal',
          fontSize: '22',
});
    }

Enter fullscreen mode Exit fullscreen mode

We imported our FontFamily, defined FontWeight and specified fontSize.

Hiding Controls

By now, you know you can see the different controls in the text layer such as scale, rotate, etc.

We may not need all of them.

How do we hide them?

Here's what I found in Codepen.

  var HideControls = {
          'tl':true, //topleft
          'tr':true, //topright
          'bl':true, //bottomleft
          'br':true, //bottomright
          'ml':false, //middleleft
          'mt':false, //middletop
          'mr':false, //middleright
          'mb':false, //middlebuttom
          'mtr':false //middlerotate
      };

Enter fullscreen mode Exit fullscreen mode

First, you specify what you want to show and what you don't want.

I have decided to show only four controls on four different directions.

Just set either true or false depending on your desire.

Next, before you add the textelement to canvas, add this.

textBox.setControlsVisibility(HideControls);
Enter fullscreen mode Exit fullscreen mode

You'll get the code, relax.

Delete Text

To delete the item, you get the active element in the Canvas and remove it.

document.getElementById('delete').onclick = function() {
var activeObject = canvas.getActiveObjects();
canvas.discardActiveObject();
canvas.remove(...activeObject);

      };

Enter fullscreen mode Exit fullscreen mode

Author's note: I wrote this in my class. My teacher pointed I wasn't paying attention throughout the whole class duration.

Anyway, we continue.

This code removes the active selected objects from the canvas.

I don't know what discard active object does.

Download Item

  var save = document.getElementById('downloader');
        save.addEventListener('click', sveimg, false);

        function sveimg(e) {
            this.href = canvas.toDataURL({
                format: 'png',
                quality: 0.8
            });
            this.download = 'canvas.png'
        }

Enter fullscreen mode Exit fullscreen mode

First we attach an event listener to 'downloader' ID.

On click, it will trigger a function which will add the image data to the 'href' of the download link.

And the file will be downloaded.

The format of the download file will be PNG and will be named 'canvas.png'.

Complete Code

<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;700&display=swap" rel="stylesheet">

<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>

<div class = "buttons">

  <button class = "button" type="button" onclick="addTextToCanvas('quote')">Add Quote</button>

  <button class = "button" type="button" onclick="addTextToCanvas('author')">Add Author</button>

  <a href="" class = "button" onclick = "convertToImage()" id='downloader'>Download</a>

  <button type="button" id='delete' name="button">delete text layer</button>

</div>

<canvas id="myCanvas" width="800" height="500" style="border:1px solid #000000; margin-top  : 30vh;  margin-left : 25%">
</canvas>
<script src="fabric.js" charset="utf-8"></script>
<script type="text/javascript">


  const canvas = new fabric.Canvas('myCanvas');
  canvas.backgroundColor = '#ffffff';
  //background color of canvas is white. If not mentioned, it will be transparent.


  var HideControls = {
          'tl':true, //topleft
          'tr':true, //topright
          'bl':true, //bottomleft
          'br':true, //bottomright
          'ml':false, //middleleft
          'mt':false, //middletop
          'mr':false, //middleright
          'mb':false, //middlebuttom
          'mtr':false //middlerotate
      };


//function to add text
//function is triggered by the button
  function addTextToCanvas(value){
    console.log(value);
    let textBox;

    if(value.trim()=='quote'){
      textBox = new fabric.IText("In order to love who you are, \nyou cannot hate the experiences \nthat shaped you.", {
          left : 70,
          top: 100,
          fontFamily: 'Inter',
          fontWeight: 'Bold',
          cornerColor: 'blue',
          cornerStrokeColor: 'red',
          borderColor: 'red',
          cornerSize: 12,
          padding: 10,
          textAlign: 'left',
          cornerStyle: 'circle',
          borderDashArray: [0, 0]
        });

    }else{
      textBox = new fabric.IText("Andrea Dykstra", {
          left : 70,
          top: 350,
          fontFamily: 'Inter',
          fontWeight: 'Normal',
          fontSize: '22',
          cornerColor: 'blue',
          cornerStrokeColor: 'red',
          borderColor: 'red',
          cornerSize: 12,
          padding: 10,
          textAlign: 'left',
          cornerStyle: 'circle',
          borderDashArray: [0, 0]});

    }

    canvas.add(textBox); //add the textbox variable into the canvas

    textBox.setControlsVisibility(HideControls); //hide controls such as scale, rotate, etc

    canvas.setActiveObject(textBox); //automatically selects the item in the canvas. Try without using this code.

  }




        var save = document.getElementById('downloader');
        save.addEventListener('click', sveimg, false);

        function sveimg(e) {
            this.href = canvas.toDataURL({
                format: 'png',
                quality: 0.8
            });
            this.download = 'canvas.png'
        }




 document.getElementById('delete').onclick = function() {
   var activeObject = canvas.getActiveObjects();

canvas.discardActiveObject();
canvas.remove(...activeObject);

      };







</script>

<style media="screen">

  body{
  color : black;
  font-family: 'Inter', sans-serif;
}


</style>

Enter fullscreen mode Exit fullscreen mode

Conclusion

Demo: https://codepen.io/isneuu/pen/XWgxLPv

Fabric Js is a nice one.

Here are more resources to learn:

http://fabricjs.com/ (Official documentation)

https://codepen.io/search/pens?q=fabric+js (Simple Fabric Js projects with code)

https://github.com/search?q=fabric+js (Hundreds of projects about Fabric Js)

Thanks for reading.

Connect with me at https://isneuu.com

The contents of this code were written with the help of projects in Codepen and FabricJs examples.

Thank you.

Cover image: Steve Johnson on Unsplash

Top comments (0)