Categories
FabricJS

Canvas Editor in FabricJS

Beta version of Canvas Editor.

Get source code? For more information about the system. You can contact me @ Email – larrydaveemol@gmail.com

Let me know what you need just leave a message/comment and I will do my very best to make that happen.

Categories
FabricJS

Image Send Backward / Forward, FlipX / FlipY, Clone and Delete object, Add Background Image with fabric JS

Another fabric JS function upload image to canvas with size validation, send image backward and forward, mirroring object horizontally and Vertically, Cloning Object, Delete Object, Add background image and Save Canvas to blob using canvas-toBlob and FileSaver JS library.

Read fabric library documentation

Create Canvas Page

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Proghubsterzeak</title>
  <link rel="stylesheet" href="./assets/bootstrap/css/bootstrap.min.css">
  <link rel="stylesheet" href="./assets/izitoast/dist/css/iziToast.min.css">
  <style>
    .card {
      max-width: 100px;
      width: 100%;
    }
  </style>
</head>

<body>
  <header>
    <nav class="navbar navbar-light bg-light">
      <span class="navbar-text">
        <a href="https://proghubsterzeak.com/"> https://proghubsterzeak.com</a>
      </span>
    </nav>
  </header>

  <main class="my-5">
    <section>
      <div class="container">
        <div class="row">
          <div class="col-lg-4 border border-primary rounded-lg">
            <div class="col-lg-12 h-100 d-flex align-items-center">
              <div class="row">
                <div class="col-lg-12 px-0 my-4">
                  <input id="img-upload" class="form-control" accept="image/*" type="file" multiple="">
                </div>
                <div class="col-lg-12 px-0">
                  <div class="btn-group" role="group" aria-label="Basic example">
                    <button type="button" class="btn btn-secondary objectback border">Send to Back</button>
                    <button type="button" class="btn btn-secondary objectfront border">Send to Front</button>
                  </div>
                  <div class="btn-group mt-2" role="group" aria-label="Basic example">
                    <button type="button" class="btn btn-secondary objectfx border">FlipX</button>
                    <button type="button" class="btn btn-secondary objectfy border">FlipY</button>
                  </div>
                </div>
                <div class="col-lg-12 px-0 my-4">
                  <div class="btn-group" role="group" aria-label="Basic example">
                    <button type="button" class="btn btn-secondary objectclone border">Clone</button>
                    <button type="button" class="btn btn-danger objectdel border">Delete</button>
                  </div>
                </div>
                <div class="col-lg-12 px-0 my-4 d-flex flex-wrap">
                  <h6 class="d-block w-100"> Background</h6>
                  <div class="card ml-0 my-2">
                    <a href="javascript:void(0)" class="bg-canvas"><img class="card-img-top img-fluid"
                        src="./assets/images/bg1.jpg"></a>
                  </div>
                  <div class="card m-2">
                    <a href="javascript:void(0)" class="bg-canvas"><img class="card-img-top img-fluid"
                        src="./assets/images/bg2.jpg"></a>
                  </div>
                </div>
                <div class="col-lg-12 px-0 my-4">
                  <div class="btn-group btn-block" role="group" aria-label="Basic example">
                    <button type="button" class="btn btn-success save-image border">Save Image</button>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <div class=" col-lg-8 justify-content-center">
            <canvas width="745" height="492px" id="my-canvas"></canvas>
          </div>
        </div>
      </div>
    </section>
  </main>

  <script src="./assets/jquery/jquery.min.js"></script>
  <script src="./assets/izitoast/dist/js/iziToast.min.js"></script>
  <script src="./assets/fabric/fabric.min.js"></script>
  <script src="./assets/fabric/fontfaceobserver.js"></script>
  <script src="./assets/fabric/canvas-toBlob.js"></script>
  <script src="./assets/fabric/FileSaver.min.js"></script>
  <script src="./assets/js/custom.js"></script>
</body>

</html>

Create JS Function

(function ($) {

  fabric.Object.prototype.set({
    borderColor: '#fff',
    cornerColor: '#fff',
    cornerSize: 13,
    cornerStyle: 'circle',
    transparentCorners: false,
    padding: 5,
    rotatingPointOffset: 20,
    // borderDashArray: [5, 5],
    objectCaching: true,
    hoverCursor: 'pointer'
  });

  let canvas = new fabric.Canvas('my-canvas', {
    containerClass: 'canvas-wrapper',
    preserveObjectStacking: true,
    backgroundColor: '#000'
  });

  $("#img-upload").on('change', function (e) {
    let files = e.target.files
    var reader = new FileReader();

    reader.onload = function (event) {
      var imgObj = new Image();
      imgObj.src = event.target.result;
      imgObj.onload = function () {

        let size = 15000
        let err = "";
        for (var x = 0; x < files.length; x++) {
          if (files[x].size > size) {
            err += files[x].type + ' is too large, please pick a smaller file\n';
          }
        }
        if (err !== '') {
          event.target.value = null
          flashMessage(err);
          return false
        }

        fabric.Image.fromURL(imgObj.src, function (oImg) {

          if (imgObj.width >= 200) {
            oImg.set({
              scaleX: .20,
              scaleY: .20
            });
          }

          canvas.add(oImg).setActiveObject(oImg);
          canvas.centerObject(oImg);
        }, {
          crossOrigin: 'anonymous'
        });

      };
    };
    reader.readAsDataURL(e.target.files[0]);

  })

  $(".bg-canvas").on('click', function () {
    let bg = $(this).find("img").attr('src');
    fabric.Image.fromURL(bg, function (img) {
      canvas.setBackgroundImage(img, canvas.renderAll.bind(canvas), {
        scaleX: canvas.width / img.width,
        scaleY: canvas.height / img.height
      });
    });
  })

  $(".objectback").on('click', function () {
    let activeObj = canvas.getActiveObject();
    if (activeObj != null) {
      canvas.sendToBack(activeObj);
    } else {
      return false;
    }
  })

  $(".objectfront").on('click', function () {
    let activeObj = canvas.getActiveObject();
    if (activeObj != null) {
      canvas.bringToFront(activeObj);
    } else {
      return false;
    }
  })

  $(".objectdel").on('click', function () {
    let activeObj = canvas.getActiveObjects();
    if (activeObj != null) {
      activeObj.forEach(function (object) {
        canvas.remove(object);
      });

      canvas.discardActiveObject();
      canvas.renderAll();
      canvas.requestRenderAll();
    } else {
      return false;
    }
  })

  $(".objectclone").on('click', function () {
    let activeObject = canvas.getActiveObject();
    if (activeObject != null) {
      activeObject.clone(function (cloned) {
        canvas.discardActiveObject();
        cloned.set({
          top: cloned.top + 20,
          evented: true
        });
        if (cloned.type === 'activeSelection') {
          // active selection needs a reference to the canvas.
          cloned.canvas = canvas;
          cloned.forEachObject(function (obj) {
            canvas.add(obj);
          });
          cloned.setCoords();
        } else {
          canvas.add(cloned);
        }
        canvas.setActiveObject(cloned);
        canvas.requestRenderAll();
      });
    } else {
      err = "Please select object";
      flashMessage(err);
      return false;
    }
  })

  $(".objectfx").on('click', function () {
    let activeObject = canvas.getActiveObject();
    if (activeObject != null) {

      activeObject.toggle('flipX');
      canvas.renderAll();

    } else {
      err = "Please select object";
      flashMessage(err);
      return false;
    }
  })

  $(".objectfy").on('click', function () {
    let activeObject = canvas.getActiveObject();
    if (activeObject != null) {

      activeObject.toggle('flipY');
      canvas.renderAll();

    } else {
      err = "Please select object";
      flashMessage(err);
      return false;
    }
  })

  $(".save-image").on('click', function () {
    // let cv = canvas.toDataURL();
    // console.log(cv);

    canvas.discardActiveObject();
    canvas.renderAll();
    $("#my-canvas").get(0).toBlob(function (blob) {
      saveAs(blob, "myIMG.png");
    });
  })

  /*Flash Message*/
  function flashMessage(err) {
    iziToast.warning({
      title: 'warning :',
      message: err,
      timeout: 4000,
      animateInside: true,
      position: 'topRight',
    });
  }

})(jQuery);

If you want to get source code, please click Download Code button on below link. For more information about the system. You can contact me @ Email – larrydaveemol@gmail.com

Let me know what you need just leave a message/comment and I will do my very best to make that happen. I hope this codes will help you. Enjoy Coding!

Categories
FabricJS

Change Background Color and Text Properties with fabric JS

Here is another example of fabric JS that can change canvas background color and text properties I’m using Font Face Observer to Load all fonts and jsColor Picker.

Create Canvas Page

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Proghubsterzeak</title>
  <link rel="stylesheet" href="./assets/bootstrap/css/bootstrap.min.css">
  <link rel="stylesheet" href="./assets/izitoast/dist/css/iziToast.min.css">
  <link rel="stylesheet" href="./assets/font/fonts.css">
</head>

<body>
  <header>
    <nav class="navbar navbar-light bg-light">
      <span class="navbar-text">
        <a href="https://proghubsterzeak.com/"> https://proghubsterzeak.com</a>
      </span>
    </nav>
  </header>

  <main class="my-5">
    <section>
      <div class="container">
        <div class="row">
          <div class="col-lg-4">
            <div class="col-lg-12 h-100 d-flex align-items-center">
              <div class="row">
                <div class="col-lg-12 px-0 my-4">
                  <label for="">Select Font</label>
                  <select class="form-control" name="font-family" id="font-family">
                    <option value="AbhayaLibre-Regular">AbhayaLibre-Regular</option>
                    <option value="Almond-Regular">Almond-Regular</option>
                    <option value="Berg-Regular">Berg-Regular</option>
                    <option value="Gobold-Regular">Gobold-Regular</option>
                    <option value="HelveticaNeue">HelveticaNeue</option>
                    <option value="Montserrat-Regular">Montserrat-Regular</option>
                    <option value="LeagueGothic-Regular">LeagueGothic-Regular</option>
                    <option value="Nunito-Regular">Nunito-Regular</option>
                    <option value="Poppins-Regular">Poppins-Regular</option>
                    <option value="Roboto-Regular">Roboto-Regular</option>
                    <option value="SinkinSans-Regular">SinkinSans-Regular</option>
                  </select>
                </div>
                <div class="btn-group btn-group-toggle" data-toggle="buttons">
                  <a class="btn btn-secondary btn-block rounded-0 border text-bold font-weight-bold mt-0"
                    href="javascript:void(0)">B</a>
                  <a class="btn btn-secondary btn-block rounded-0 border text-italic font-italic mt-0"
                    href="javascript:void(0)">I</a>
                  <a class="btn btn-secondary btn-block rounded-0 border text-underline mt-0" href="javascript:void(0)"
                    style="text-decoration: underline">U</a>
                </div>
                <div class="col-lg-12 px-0 my-2 d-flex">
                  <div class="form-group pr-2">
                    <label for="my-input">Text Color</label>
                    <input class="text-color rounded-0 form-control jscolor {onFineChange:'textcolor(this)'}"
                      value="80B3FF">
                  </div>
                  <div class="form-group pr-2">
                    <label for="my-input">Backround Color</label>
                    <input class="bg-color rounded-0 form-control jscolor {onFineChange:'bgcolor(this)'}"
                      value="A4FF96">
                  </div>
                </div>
              </div>
            </div>
          </div>
          <div class=" col-lg-8 justify-content-center">
            <canvas width="745" height="450" id="my-canvas"></canvas>
          </div>
        </div>
      </div>
    </section>
  </main>

  <script src="./assets/jquery/jquery.min.js"></script>
  <script src="./assets/bootstrap/js/bootstrap.bundle.js"></script>
  <script src="./assets/jsColor/jscolor.js"></script>
  <script src="./assets/izitoast/dist/js/iziToast.min.js"></script>
  <script src="./assets/fabric/fabric.min.js"></script>
  <script src="./assets/fabric/fontfaceobserver.js"></script>
  <script src="./assets/js/custom.js"></script>
</body>

</html>

Create JS Function

(function ($) {

  fabric.Object.prototype.set({
    borderColor: '#fff',
    cornerColor: '#fff',
    cornerSize: 13,
    cornerStyle: 'circle',
    transparentCorners: false,
    padding: 5,
    rotatingPointOffset: 20,
    // borderDashArray: [5, 5],
    objectCaching: true,
    hoverCursor: 'pointer'
  });

  let canvas = new fabric.Canvas('my-canvas', {
    containerClass: 'canvas-wrapper',
    preserveObjectStacking: true,
    backgroundColor: '#000'
  });

  var fonts = ["AbhayaLibre-Regular", "Almond-Regular", "Berg-Regular", "Gobold-Regular", "HelveticaNeue", "Montserrat-Regular", "LeagueGothic-Regular", "Nunito-Regular", "Poppins-Regular", "Roboto-Regular", "SinkinSans-Regular"];

  // Load all fonts using Font Face Observer
  Promise.all(
    fonts.map(
      font => new FontFaceObserver(font).load()
    )
  ).then(function () {
    fonts.unshift('Montserrat-Regular');
  }, function (e) {
    console.log(e);
  });

  let text = new fabric.Textbox('Proghubsterzeak', {
    fill: '#ffffff',
    fontSize: 50,
    lineHeight: 1,
    textAlign: 'center',
    fontFamily: 'Nunito-Regular',
    charSpacing: 0,
    width: 450
  });

  canvas.add(text).setActiveObject(text);;
  text.center();

  $("#font-family").bind('change', 'click', function (e) {
    let activeObj = canvas.getActiveObject();

    if (activeObj != null) {

      activeObj.set("fontFamily", e.target.value);
      canvas.requestRenderAll();

    } else {
      flashMessage();
      return false;
    }

  })

  $(".text-bold").click(function () {
    let activeObj = canvas.getActiveObject();
    let sel_active = $(this).hasClass('active');

    if (activeObj != null) {
      if (sel_active == false) {
        activeObj.set({
          fontWeight: 'Bold'
        });
      } else {
        activeObj.set({
          fontWeight: 'Normal'
        });
      }
    } else {
      flashMessage();
      return false;
    }

    canvas.renderAll();
  });

  $(".font-italic").click(function () {
    let activeObj = canvas.getActiveObject();
    let sel_active = $(this).hasClass('active');

    if (activeObj != null) {
      if (sel_active == false) {
        activeObj.set({
          fontStyle: 'Italic'
        });
      } else {
        activeObj.set({
          fontStyle: ''
        });
      }
    } else {
      flashMessage();
      return false;
    }

    canvas.renderAll();
  });

  $(".text-underline").click(function () {
    let activeObj = canvas.getActiveObject();
    let sel_active = $(this).hasClass('active');

    if (activeObj != null) {
      if (sel_active == false) {
        activeObj.set({
          underline: true,
          linethrough: false,
        });
      } else {
        activeObj.set({
          underline: false,
        });
      }
    } else {
      flashMessage();
      return false;
    }

    canvas.renderAll();
  });

  window.textcolor = function (jscolor) {
    let activeObj = canvas.getActiveObject();
    
    if (activeObj != null) {
      activeObj.set({
        fill: '#' + jscolor
      });

      canvas.renderAll();
    } else {
      return false;
    }
  };

  window.bgcolor = function (jscolor) {
    canvas.backgroundColor = '#' + jscolor
    canvas.renderAll();
  };

  /*Flash Message*/
  function flashMessage() {
    iziToast.warning({
      title: 'warning :',
      message: 'No object selected',
      timeout: 4000,
      animateInside: true,
      position: 'topRight',
    });
  }

})(jQuery);

If you want to get source code, please click Download Code button on below link. For more information about the system. You can contact me @ Email – larrydaveemol@gmail.com

Let me know what you need just leave a message/comment and I will do my very best to make that happen. I hope this codes will help you. Enjoy Coding!

Categories
FabricJS

Object Alignment with fabric JS

Here is the simple implementation in canvas application that can move selected object by using arrow keys and set option alignment triggered from the button.

Create Canvas Page

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Proghubsterzeak</title>
  <link rel="stylesheet" href="./assets/bootstrap/css/bootstrap.min.css">
  <link rel="stylesheet" href="./assets/izitoast/dist/css/iziToast.min.css">
</head>

<body>
  <header>
    <nav class="navbar navbar-light bg-light">
      <span class="navbar-text">
        <a href="https://proghubsterzeak.com/"> https://proghubsterzeak.com</a>
      </span>
    </nav>
  </header>

  <main class="my-5">
    <section>
      <div class="container">
        <div class="row">
          <div class="col-lg-4">
            <div class="col-lg-12 h-100 d-flex align-items-center">
              <div class="row">
                <div class="col-lg-4 px-0">
                  <a class="btn btn-secondary btn-block rounded-0 border align-sel" align-data="tl"
                    href="javascript:void(0)">TL</a>
                </div>
                <div class="col-lg-4 px-0">
                  <a class="btn btn-secondary btn-block rounded-0 border align-sel" align-data="tc"
                    href="javascript:void(0)">TOP</a>
                </div>
                <div class="col-lg-4 px-0">
                  <a class="btn btn-secondary btn-block rounded-0 border align-sel" align-data="tr"
                    href="javascript:void(0)">TR</a>
                </div>
                <div class="col-lg-4 px-0">
                  <a class="btn btn-secondary btn-block rounded-0 border align-sel" align-data="cl"
                    href="javascript:void(0)">CL</a>
                </div>
                <div class="col-lg-4 px-0">
                  <a class="btn btn-secondary btn-block rounded-0 border align-sel" align-data="c"
                    href="javascript:void(0)">Center</a>
                </div>
                <div class="col-lg-4 px-0">
                  <a class="btn btn-secondary btn-block rounded-0 border align-sel" align-data="cr"
                    href="javascript:void(0)">CR</a>
                </div>
                <div class="col-lg-4 px-0">
                  <a class="btn btn-secondary btn-block rounded-0 border align-sel" align-data="bl"
                    href="javascript:void(0)">BL</a>
                </div>
                <div class="col-lg-4 px-0">
                  <a class="btn btn-secondary btn-block rounded-0 border align-sel" align-data="bc"
                    href="javascript:void(0)">BOTTOM</a>
                </div>
                <div class="col-lg-4 px-0">
                  <a class="btn btn-secondary btn-block rounded-0 border align-sel" align-data="br"
                    href="javascript:void(0)">BR</a>
                </div>
              </div>
            </div>
          </div>
          <div class="col-lg-8 justify-content-center">
            <canvas width="745" height="450" id="my-canvas"></canvas>
          </div>
        </div>
      </div>
    </section>
  </main>

  <script src="./assets/jquery/jquery.min.js"></script>
  <script src="./assets/izitoast/dist/js/iziToast.min.js"></script>
  <script src="./assets/fabric/fabric.min.js"></script>
  <script src="./assets/js/custom.js"></script>
</body>

</html>

Create JS Function

(function ($) {

  fabric.Object.prototype.set({
    borderColor: '#fff',
    cornerColor: '#fff',
    cornerSize: 13,
    cornerStyle: 'circle',
    transparentCorners: false,
    padding: 5,
    rotatingPointOffset: 20,
    // borderDashArray: [5, 5],
    objectCaching: true,
    hoverCursor: 'pointer'
  });

  let canvas = new fabric.Canvas('my-canvas', {
    containerClass: 'canvas-wrapper',
    preserveObjectStacking: true,
    backgroundColor: '#000'
  });

  let circ = new fabric.Circle({
    radius: 50,
    fill: 'pink'
  });

  canvas.add(circ).setActiveObject(circ);;
  circ.center();


  $(".align-sel").click(function () {

    var activeObj = canvas.getActiveObject();
    var sel_value = $(this).attr('align-data');

    switch (sel_value) {
      case 'tl':
        if (activeObj != null) {

          activeObj.set({
            top: 10,
            left: 10,
          });

        } else {
          flashMessage();
          return false;
        }
        break;

      case 'tc':
        if (activeObj != null) {

          activeObj.set({
            top: 10,
          });
          activeObj.centerH();

        } else {
          flashMessage();
          return false;
        }
        break;

      case 'tr':
        if (activeObj != null) {

          activeObj.set({
            top: 10,
            left: canvas.width - activeObj.width - 10
          });

        } else {
          flashMessage();
          return false;
        }
        break;

      case 'cl':
        if (activeObj != null) {

          activeObj.set({
            left: 10
          });
          activeObj.centerV();

        } else {
          flashMessage();
          return false;
        }
        break;

      case 'c':
        if (activeObj != null) {

          activeObj.center();

        } else {
          flashMessage();
          return false;
        }
        break;

      case 'cr':
        if (activeObj != null) {

          activeObj.set({
            left: canvas.width - activeObj.width - 10
          });
          activeObj.centerV();

        } else {
          flashMessage();
          return false;
        }
        break;

      case 'bl':
        if (activeObj != null) {

          activeObj.set({
            top: canvas.height - activeObj.height - 10,
            left: 10
          });

        } else {
          flashMessage();
          return false;
        }
        break;

      case 'bc':
        if (activeObj != null) {

          activeObj.set({
            top: canvas.height - activeObj.height - 10,
          });
          activeObj.centerH();

        } else {
          flashMessage();
          return false;
        }
        break;

      case 'br':
        if (activeObj != null) {

          activeObj.set({
            left: canvas.width - activeObj.width - 10,
            top: canvas.height - activeObj.height - 10,
          });

        } else {
          flashMessage();
          return false;
        }
        break;
    }
    activeObj.setCoords();
    canvas.renderAll();
  });

  fabric.util.addListener(document.body, 'keydown', function (e) {
    let activeObj = canvas.getActiveObject();

    switch (e.keyCode) {
      case 38:
        /* Up arrow */
        e.preventDefault();
        if (activeObj != null) {
          activeObj.top -= 5;
          canvas.renderAll();
          activeObj.setCoords();
        } else {
          flashMessage();
          return false;
        }
        break;
      case 40:
        /* Down arrow  */
        e.preventDefault();
        if (activeObj != null) {
          activeObj.top += 5;
          canvas.renderAll();
          activeObj.setCoords();
        } else {
          flashMessage();
          return false;
        }
        break;
      case 37:
        /* Left arrow  */
        if (activeObj != null) {
          activeObj.left -= 5;
          canvas.renderAll();
          activeObj.setCoords();
        } else {
          flashMessage();
          return false;
        }
        break;
      case 39:
        /* Right arrow  */
        if (activeObj != null) {
          activeObj.left += 5;
          canvas.renderAll();
          activeObj.setCoords();
        } else {
          flashMessage();
          return false;
        }
        break;
    }
  });


  /*Flash Message*/
  function flashMessage() {
    iziToast.warning({
      title: 'warning :',
      message: 'No object selected',
      timeout: 4000,
      animateInside: true,
      position: 'topRight',
    });
  }

})(jQuery);

If you want to get source code, please click Download Code button on below link. For more information about the system. You can contact me @ Email – larrydaveemol@gmail.com

Let me know what you need just leave a message/comment and I will do my very best to make that happen. I hope this codes will help you. Enjoy Coding!

Categories
FabricJS

Create shapes with fabric JS

This is a basic canvas application that can create shape and added to the canvas triggered from the button.

Create Canvas Page

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Proghubsterzeak</title>
  <link rel="stylesheet" href="./assets/bootstrap/css/bootstrap.min.css">
  <link rel="stylesheet" href="./assets/izitoast/dist/css/iziToast.min.css">
</head>

<body>
  <header>
    <nav class="navbar navbar-light bg-light">
      <span class="navbar-text">
        <a href="https://proghubsterzeak.com/"> https://proghubsterzeak.com</a>
      </span>
    </nav>
  </header>

  <main class="my-5">
    <section>
      <div class="container">
        <div class="btn-shapes d-flex justify-content-center my-3">
          <a class="btn btn-danger mx-2 shape-sel" shape-data="circ" href="javascript:void(0)">Circle</a>
          <a class="btn btn-success mx-2 shape-sel" shape-data="rect" href="javascript:void(0)">Rectangle</a>
          <a class="btn btn-warning mx-2 shape-sel" shape-data="tria" href="javascript:void(0)">Triangle</a>
          <a class="btn btn-primary mx-2 shape-sel" shape-data="line" href="javascript:void(0)">Line</a>
          <a class="btn btn-secondary mx-2 shape-sel" shape-data="poly" href="javascript:void(0)">Polygon</a>
        </div>
        <div class="row justify-content-center">
          <canvas width="767" height="450" id="my-canvas"></canvas>
        </div>
      </div>
    </section>
  </main>

  <script src="./assets/jquery/jquery.min.js"></script>
  <script src="./assets/izitoast/dist/js/iziToast.min.js"></script>
  <script src="./assets/fabric/fabric.min.js"></script>
  <script src="./assets/js/custom.js"></script>
</body>

</html>

Create JS Function

(function ($) {
  let canvas = new fabric.Canvas('my-canvas', {
    containerClass: 'canvas-wrapper',
    preserveObjectStacking: true,
    backgroundColor: '#ccc'
  });

  let circ = new fabric.Circle({
    radius: 100,
    fill: 'red'
  });

  canvas.add(circ);
  circ.center();

  $(".shape-sel").click(function () {

    var activeObj = canvas.getActiveObject();
    var sel_value = $(this).attr('shape-data');

    switch (sel_value) {
      case 'circ':
        if (activeObj != null) {

          canvas.remove(activeObj);

          let shape = new fabric.Circle({
            radius: 100,
            fill: 'red'
          });
          canvas.add(shape);
          shape.center();

        } else {
          flashMessage();
          return false;
        }
        break;

      case 'rect':
        if (activeObj != null) {

          canvas.remove(activeObj);

          let shape = new fabric.Rect({
            fill: 'green',
            width: 400,
            height: 200,
          });
          canvas.add(shape);
          shape.center();

        } else {
          flashMessage();
          return false;
        }
        break;

      case 'tria':
        if (activeObj != null) {

          canvas.remove(activeObj);

          let shape = new fabric.Triangle({
            fill: 'yellow',
            width: 200,
            height: 200,
          });
          canvas.add(shape);
          shape.center();

        } else {
          flashMessage();
          return false;
        }
        break;

      case 'line':
        if (activeObj != null) {

          canvas.remove(activeObj);

          let shape = new fabric.Line([10, 100, 300, 200], {
            stroke: 'blue'
          });
          canvas.add(shape);
          shape.center();

        } else {
          flashMessage();
          return false;
        }
        break;

      case 'poly':
        if (activeObj != null) {

          canvas.remove(activeObj);

          let shape = new fabric.Polygon([
            { x: 200, y: 0 },
            { x: 250, y: 50 },
            { x: 250, y: 100 },
            { x: 150, y: 100 },
            { x: 150, y: 50 }], {
            left: 250,
            top: 150,
            angle: 0,
            fill: 'gray'
          });
          canvas.add(shape);
          shape.center();

        } else {
          flashMessage();
          return false;
        }
        break;
    }
  });

  /*Flash Message*/
  function flashMessage() {
    iziToast.warning({
      title: 'warning :',
      message: 'No object selected',
      timeout: 4000,
      animateInside: true,
      position: 'topRight',
    });
  }

})(jQuery);

If you want to get source code, please click Download Code button on below link. For more information about the system. You can contact me @ Email – larrydaveemol@gmail.com

Let me know what you need just leave a message/comment and I will do my very best to make that happen. I hope this codes will help you. Enjoy Coding!