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!

Share this
  •  
  •  
  •  
  •  
  •  
  •  
  • 42
    Shares

Leave a Reply

Your email address will not be published. Required fields are marked *