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!