Categories
PHP

Login and Registration using PHP Ajax

Table structure for table `users`

CREATE TABLE `users` (
  `id` int(11) NOT NULL,
  `username` varchar(50) NOT NULL,
  `password` varchar(255) NOT NULL,
  `created_at` datetime DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Table structure for table `serial`

CREATE TABLE `serial` (
  `serial_key` varchar(25) NOT NULL,
  `serial_value` varchar(100) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
<?php
    class Database{ 
        private $db_host = 'localhost';
        private $db_name = 'db_login';
        private $db_username = 'root';
        private $db_password = '';
        
        public function dbConnection(){
            try{
                $conn = new PDO('mysql:host='.$this->db_host.';dbname='.$this->db_name,$this->db_username,$this->db_password);
                $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
                return $conn;
            }
            catch(PDOException $e){
                echo "Connection error ".$e->getMessage(); 
                exit;
            } 
        }
    }
?>
<?php
    require 'database.php';
   
    function GetWebsiteName() {
        $db_connection = new Database();
        $conn = $db_connection->dbConnection();

        $param = "WEBSITE_NAME";
        $stmt = $conn->prepare("SELECT * FROM serial");
        $stmt->bindParam(1, $param, PDO::PARAM_STR);
        
        $stmt->execute();
        $results=$stmt->fetchAll(PDO::FETCH_ASSOC);
        $serialValue = $results[0]['serial_value'];

        return $serialValue;
    }
?>
<?php
	session_start();

	require 'database.php';
    $db_connection = new Database();
    $conn = $db_connection->dbConnection();

    $post_body = file_get_contents('php://input');
    $data = json_decode($post_body); 

    // Extract the Data Fields
    if (isset($data->username)) $username = $data->username;
    if (isset($data->password)) $password = $data->password;

    if (!isset($username)) $username = "";
    if (!isset($password)) $password = "";

    $stmt = $conn->prepare("SELECT * FROM users WHERE username = '$username' and password  = '$password'");
   
    $stmt->bindParam(1, $username, PDO::PARAM_STR);
    $stmt->bindParam(2, $password, PDO::PARAM_STR);
    $stmt->execute();
    $results=$stmt->fetchAll(PDO::FETCH_ASSOC);

    $msgResult = "Success";
    if($msgResult == "Success"){
    	$userID = $results[0]['id'];
    	$username = $results[0]['username'];
    
    	// Set Session variables
    	$_SESSION['USERID'] = $userID;
    	$_SESSION['USERNAME'] = $username;
  
    	echo "success";
    } else {
    	echo "failed";
    }
?>
<?php
	// start session
	session_start();
	// Destroy user session
	unset($_SESSION['USERID']);
	unset($_SESSION['USERNAME']);

	// Redirect to index.php page
	header("Location: ../index.php");
?>
<?php
	session_start();

	require 'database.php';
    $db_connection = new Database();
    $conn = $db_connection->dbConnection();

    $post_body = file_get_contents('php://input');
    $data = json_decode($post_body); 

    // Extract the Data Fields
    if (isset($data->username)) $username = $data->username;
    if (isset($data->password)) $password = $data->password;

    if (!isset($username)) $username = "";
    if (!isset($password)) $password = "";

    $statement = $conn->prepare("SELECT * FROM users WHERE username='$username'");
    $statement->execute();
    $results = $statement->fetchColumn();
    if ($results == 0) {
        $statement = $conn->prepare("INSERT INTO users (username, password) 
        VALUES (?, ?)");
        $statement->bindParam(1, $username, PDO::PARAM_STR);
        $statement->bindParam(2, $password, PDO::PARAM_STR);
        $statement->execute();
        echo "success";
    } else {
        echo "failed";
    }
?>
<?php 
    session_start();
    require_once('library/functions.php');

    if ((isset($_SESSION['USERID']))) {
      header("Location: home.php");
    } 
?>

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

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title><?php echo GetWebsiteName(); ?></title>
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
  <link rel="stylesheet" href="./assets/izitoast/dist/css/iziToast.min.css">
  <link rel="stylesheet" href="./assets/css/custom.css">
  <link href="https://fonts.googleapis.com/css2?family=Montserrat:wght@400;700&display=swap" rel="stylesheet">
</head>

<body>
  <main class="py-5 d-flex align-items-center justify-content-center h-100">
    <div class="col-lg-8 col-md-10 bg-login py-3">
      <div class="row">
        <div class="col-lg-6 column-1">
          <div class="card border-0 shadow-lg">
            <div class="card-body py-5">
              <h3 class="card-title">Login</h3>
              <p class="card-text">Dont Have an Account? <a class="reg-user" href="#"> Create your Account</a></p>
              <form id="login_form" method="post">
                <div class="form-group">
                  <input id="email" class="form-control" type="email" name="email" placeholder="Enter Username">
                </div>
                <div class="form-group">
                  <input id="password" class="form-control" type="password" name="password"
                    placeholder="Enter Password">
                </div>
                <div class="btn-wrapper text-right">
                  <button class="btn btn-primary" href="javascript:void(0)" type="submit" id="login_button">Sign
                    In</button>
                </div>
              </form>
            </div>
          </div>
        </div>
        <div class="col-lg-6 column-0" style="display:none">
          <div class="card border-0 shadow-lg">
            <div class="card-body py-5">
              <h3 class="card-title">Register Account</h3>
              <p class="card-text">Do You Have an Account? <a class="login-user" href="#"> Login</a></p>
              <form id="reg_form" method="post">
                <div class="form-group">
                  <input id="reg-email" class="form-control" type="email" name="reg-email" placeholder="Enter Username">
                </div>
                <div class="form-group">
                  <input id="reg-password" class="form-control" type="password" name="reg-password"
                    placeholder="Enter Password">
                </div>
                <div class="form-group">
                  <input id="reg-re-password" class="form-control" type="password" name="reg-re-password"
                    placeholder="Confirm Password">
                </div>
                <div class="btn-wrapper text-right">
                  <button class="btn btn-primary" href="javascript:void(0)" type="submit">Sign
                    Up</button>
                </div>
              </form>
            </div>
          </div>
        </div>
        <div class="col-lg-6 column-2 overflow-hidden">
          <div class="card border-0 bg-transparent text-right text-white">
            <img class="card-img" src="assets/images/undraw_Directions_re_kjxs.svg" alt="">
            <div class="card-img-overlay">
              <h2 class="card-title">Welcome Back</h2>
              <p class="card-text">Simply Create your account by clicking the signup button</p>
            </div>
          </div>
        </div>
      </div>
    </div>
  </main>

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

</html>
<?php 
  session_start();
  require_once('library/functions.php');
  if (($_SESSION['USERID'] == '') || (!isset($_SESSION['USERID']))) {
    // Redirect to index.php page
    header("Location: index.php");
  } 
?>

<!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><?php echo GetWebsiteName(); ?></title>
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
  <link rel="stylesheet" href="./assets/izitoast/dist/css/iziToast.min.css">
  <link rel="stylesheet" href="./assets/css/custom.css?version:202">
  <link href="https://fonts.googleapis.com/css2?family=Montserrat:wght@400;700&display=swap" rel="stylesheet">
</head>

<body>
  <header>
    <nav class="navbar navbar-expand-lg navbar-dark bg-dark fixed-top">
      <a class="navbar-brand">Proghubsterzeak</a>
      <button class="navbar-toggler" data-target="#my-nav" data-toggle="collapse" aria-controls="my-nav"
        aria-expanded="false" aria-label="Toggle navigation">
        <span class="navbar-toggler-icon"></span>
      </button>
      <div id="my-nav" class="collapse navbar-collapse">
        <ul class="navbar-nav ml-auto">
          <li class="nav-item active">
            <a class="nav-link" href="library/logout.php">Logout <span class="sr-only">(current)</span></a>
          </li>
        </ul>
      </div>
    </nav>
  </header>
  <main class="py-5 d-flex align-items-center justify-content-center h-100">
    <h1>Welcome User</h1>
  </main>
</body>

</html>
  • 34
    Shares
Categories
HTML/CSS

Display Data in HTML table using Datatable plug-in – Visual Basic 6.0 Connected to MySQL Database

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

Categories
HTML/CSS

Login Form

I am sharing this simple Login form, responsive in all screen devices with bootstrap 4.4 that can be integrate in your projects and customize as you like I hope you’ll customize this template according to your individual project’s needs.

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

Categories
HTML/CSS

Signup Form

I am sharing this simple Signup form, responsive in all screen devices with bootstrap 4.4 that can be integrate in your projects and customize as you like I hope you’ll customize this template according to your individual project’s needs .

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

Categories
HTML/CSS

Minimal Login Form

I am sharing this simple login form, responsive in all screen devices with bootstrap 4.4 that can be integrate in your projects and customize as you like I hope you’ll customize this template according to your individual project’s needs .

<!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>Site | Login</title>
  <link rel="shortcut icon" href="assets/images/logo.png" type="image/x-icon">
  <link rel="stylesheet" href="assets/bootstrap/css/bootstrap.min.css">
  <link rel="stylesheet" href="assets/custom-fonts/style.css">
  <link rel="stylesheet" href="assets/izitoast/dist/css/iziToast.min.css">
  <link rel="stylesheet" href="assets/css/fonts.css">
  <link rel="stylesheet" href="assets/css/responsive.css">
  <link rel="stylesheet" href="assets/css/custom.css">
  <style>
  body {
    min-height: 100vh;
    position: relative;
    overflow-x: hidden;
    background: #e65c00;
    background: -webkit-linear-gradient(45deg, #e0eafc, #cfdef3);
    background: linear-gradient(45deg, #e0eafc, #cfdef3);
  }

  .column-login {
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
  }

  .card {
    box-shadow: 0px 10px 30px -10px rgba(151, 163, 184, 0.5) !important;
    -webkit-box-shadow: 0px 10px 30px -10px rgba(151, 163, 184, 0.5) !important;
    -moz-box-shadow: 0px 10px 30px -10px rgba(151, 163, 184, 0.5) !important;
    -ms-box-shadow: 0px 10px 30px -10px rgba(151, 163, 184, 0.5) !important;
    -o-box-shadow: 0px 10px 30px -10px rgba(151, 163, 184, 0.5) !important;
  }

  .crd-theme {
    background: #00B4DB;
    background: -webkit-linear-gradient(45deg, #0083B0, #00B4DB);
    background: linear-gradient(45deg, #0083B0, #00B4DB);
  }

  .show-pass {
    cursor: pointer;
  }
  </style>
</head>

<body>
  <main class="py-5">
    <section id="login-area">
      <div class="container-fluid">
        <div class="row align-items-center">
          <div class="column-login col-lg-4 mx-auto">
            <div class="card border-0">
              <div class="card-header text-center crd-theme text-white">
                <h5 class="font-weight-regular"> Login Account</h5>
                <p class="card-text">This is a secure system and you will need <br />
                  to provide your login details to access the site.</p>
              </div>
              <div class="card-body">

                <div class="row">
                  <div class="col-12 my-2">
                    <div class="input-group">
                      <div class="input-group-prepend">
                        <span class="input-group-text"><i class="cf-user-o"></i></span>
                      </div>
                      <input class="form-control" type="text" name="" placeholder="Your Email or Username"
                        aria-label="Recipient's ">
                    </div>
                  </div>
                  <div class="col-12 my-2">
                    <div class="input-group">
                      <div class="input-group-prepend">
                        <span class="input-group-text"><i class=" cf-key  "></i></span>
                      </div>
                      <input class="form-control" type="password" name="" placeholder="Your Password"
                        aria-label="Recipient's ">
                      <div class="input-group-append">
                        <span class="input-group-text bg-transparent"><i class=" cf-eye-slash show-pass"></i></span>
                      </div>
                    </div>
                  </div>
                  <div class="col-12 my-2">
                    <div class="input-group">
                      <div class="input-group-prepend mr-2">
                        <span class="input-group-text"> <input type="checkbox" name="" id=""></span>
                      </div>
                      <label>Keep me logged in</label>
                    </div>
                  </div>
                  <div class="col-12 text-right">
                    <button class="btn btn-secondary" type="submit">Login</button>
                  </div>
                </div>
              </div>
              <div class="card-footer">
                <p class="m-0"> © <span class="badge badge-primary" id="copyrightYear"></span> Name of Site</p>
              </div>
            </div>
          </div>
        </div>
      </div>
    </section>
  </main>

  <script src="assets/jquery/jquery-3.3.1.js"></script>

  <script>
  let d = new Date();
  let y = d.getFullYear();
  document.getElementById("copyrightYear").innerHTML = y;

  $(".show-pass").on('click', function() {
    $(this).toggleClass('cf-eye');
    $(this).toggleClass('cf-eye-slash');
    $(this).parent().parent().parent().find('input').toggleAttr('type', 'text', 'password');
  });

  // jquery toggle just the attribute value
  $.fn.toggleAttr = function(attr, val1, val2) {
    var test = $(this).attr(attr);
    if (test === val1) {
      $(this).attr(attr, val2);
      return this;
    }
    if (test === val2) {
      $(this).attr(attr, val1);
      return this;
    }
    // default to val1 if neither
    $(this).attr(attr, val1);
    return this;
  };
  </script>

</body>

</html>

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

Categories
HTML/CSS

Online Shopping Store

I am sharing this Online Store with bootstrap 4.4 that can be integrate in your projects and customize as you like I hope you’ll customize this template according to your individual project’s needs.

See screenshot for Online Store, responsive in all screen devices.

Download the Complete Source Codes. For more information 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

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!