How to set up face verification the easy way using HTML5 + JavaScript

How to set up face verification the easy way using HTML5 + JavaScript

<strong>Originally published by </strong><a href="https://medium.com/@matthewenubuje" target="_blank">Matthew Enubuje</a><strong> </strong><em>at&nbsp;</em><a href="https://medium.com/@matthewenubuje/how-to-set-up-face-verification-the-easy-way-using-html5-javascript-5301235e495f" target="_blank"><em>Medium</em></a>

I’ve created a very simple way to face match two images using HTML5 and JavaScript. You upload the verification picture you’d like to use, take a snapshot from the video streaming from your camera/webcam, then use a face matching API to retrieve the results. Simple.

The Github Repo

What You’ll Need:

  • A Webcam/Camera
  • Free Face Recognition API Key
  • Web Server

Before We Begin

Create a Directory For This Project

This directory will be where we put all the files.

Create a Local Web Server

In order to have full control of images, a web server is required otherwise we’d be getting a tainted canvas security error. There are several ways to do this and I’ve listed below how to do it with Python.

Python

cd C:/DIRECTORY_LOCATION & py -m http.server 8000

You should be able to access the directory through http://localhost:8000

Get Your Free API Key

We’re going to be using Facesoft’s face recognition API. Quickly sign up here to access your free API key so you can get unlimited API calls with up to two requests per minute.

Once you’ve logged in, your API key will be visible in the dashboard area.

1. Setup

Create these three files:

  • index.html
  • style.css
  • verify.js

Next right click and save the files below into that directory. These image files will be the default images for uploaded and verification pics.

SAVE AS “defaultupload.png”

SAVE AS “defaultphoto.png”

2. The HTML

Layout

Copy and paste the layout code below into your “index.html” file. This gives us our framework and design with the help of bootstrap.

<!DOCTYPE html>
<html lang="en">
<head>
  <!-- Required meta tags -->
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<!-- Style CSS -->
  <link rel="stylesheet" href="style.css">
<title>Face Verification</title>
</head>
<body>
  <!-- Page Content -->
  <div class="container">
    <div class="row">
      <div class="col-lg-12 text-center">
        <h1 class="mt-5">Face Verification</h1>
        <p class="lead">Quick and simple face verification using HTML5 and JavaScript</p>
      </div>
    </div>
    <!-- INSERT NEXT CODE HERE -->
  </div>
<!-- Verify JS -->
 <script src="verify.js"></script>
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
  <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
  <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
</body>
</html>

Images, Canvases & Buttons

We’re now creating a row and having three columns for the verification photo, the video stream, and the photo taken from the video stream. Add the code below right after the row.

Check for “INSERT NEXT CODE HERE” tag in previous code.

<div class="row justify-content-md-center">
  <div class="col-lg-4 text-center">
    <p><strong>Verification Photo</strong></p>
      <!-- Canvas For Uploaded Image -->
      <canvas id="uploadCanvas" width="300"  height="300"></canvas>
      <!-- Default Canvas Image -->
      <img src="defaultupload.png" id="uploadedPhoto" alt="upload"/>
      <!-- Upload Image Input & Upload Photo Button -->
      <input type="file" name="image-upload" accept="image/png, image/jpeg">
      <button id="upload" type="button" class="btn btn-outline-primary btn-lg">Upload Photo</button>
  </div>
  <div class="col-lg-4 text-center">
    <p><strong>Video</strong></p>
    <!-- Camera -->
    <div class="camera-container">
      <video id="video" width="100%" height="300" autoplay="true">
      </video>
    </div>
    <!-- Take Photo Button -->
    <button id="capture" type="button" class="btn btn-outline-primary btn-lg">Take Photo</button>
  </div>
  <div class="col-lg-4 text-center">
    <p><strong>Photo Taken</strong></p>
  
    <!-- Canvas For Capture Taken -->
    <canvas id="captureCanvas" width="300"  height="300"></canvas>
    <!-- Default Canvas Image -->
    <img src="defaultphoto.png" id="capturedPhoto" alt="capture" />
    <!-- Verify Photos Button -->
    <button id="verify" type="button" class="btn btn-outline-success btn-lg">Verify Photo</button>
  </div>
</div>
<!-- INSERT NEXT CODE HERE -->

API Response and Warnings

The code we’re going to add is to display the match result, score percentage, errors and warnings. Right under the last code we added, add the code below.

<div class="row">
  <div class="col-lg-12 text-center">
    <!-- API Match Result & API Percentage Score -->
    <h2 id="match" class="mt-5"></h2>
    <p id="score" class="lead"></p>
  </div>
  <div class="col-lg-12 text-center">
    <!-- Error & Warning Alerts -->
    <div class="alert alert-danger" id="errorAlert"></div>
    <div class="alert alert-warning" id="warningAlert"></div>
  </div>
</div>

3. The CSS

Add the code below to your style.css file.

.camera-container {
  max-width: 100%;
  border: 1px solid black;
}
.verification-image {
  width: 300px;
  height: auto;
  max-width: 100%;
}
.btn {
  margin-top: 10px;
}
#captureCanvas, #uploadCanvas {
  display: none;
}
input[name="image-upload"] {
  display: none;
}
#errorAlert, #warningAlert {
  display: none;
}

We’ve set the image upload input to display none as we’ll be triggering it using the upload button. Also, the IDs for the canvases have been set to display none so the default images are initially displayed.

Here is what your screen should look like:

4. The JavaScript

document.addEventListener("DOMContentLoaded", function() {
});

In the verify.js file we want to start off by adding an event listener that will run after the page loads. Every code we enter should be inside this function.

Variables

var video = document.getElementById('video'), 
captureCanvas = document.getElementById('captureCanvas'), 
uploadCanvas = document.getElementById('uploadCanvas'), 
captureContext = captureCanvas.getContext('2d'),
uploadContext = uploadCanvas.getContext('2d'),
uploadedPhoto = document.getElementById('uploadedPhoto'),
capturedPhoto = document.getElementById('capturedPhoto'),
imageUploadInput = document.querySelector('[name="image-upload"]'),
apiKey = 'INSERT_YOUR_FACESOFT_API_KEY',
errorAlert = document.getElementById('errorAlert'), AlertwarningAlert = document.getElementById('warningAlert'),
matchText = document.getElementById('match'),
scoreText = document.getElementById('score');

The variables are:

  • IDs for the video element, canvases, photos & API response
  • Selector for image input
  • Canvas contexts
  • API key

Video Stream

Here is a very simple code to access your webcam/camera and stream it into the video element. Add underneath variables.

// Stream Camera To Video Element
if(navigator.mediaDevices.getUserMedia){
  navigator.mediaDevices.getUserMedia({ video: true })
  .then(function(stream) {
    video.srcObject = stream;
  }).catch(function(error) {
    console.log(error)
  })
}

If you refresh your page, this is what you’ll see:

:D

Function 1: Set Photo To Canvas

// Set Photo To Canvas Function
function setImageToCanvas(image, id, canvas, context, width=image.width, height=image.height) {
  var ratio = width / height;
  var newWidth = canvas.width;
  var newHeight = newWidth / ratio;
  if (newHeight > canvas.height) {
    newHeight = canvas.height;
    newWidth = newHeight * ratio;
  }
  context.clearRect(0, 0, canvas.width, canvas.height);
  context.drawImage(image, 0, 0, newWidth, newHeight);
  id.setAttribute('src', canvas.toDataURL('image/png'));
}

In this function, we take in the image, id, canvas, context, width and height. We take in the width and height because to get the dimensions of the video, we must use video.videoWidth & video.videoHeight.

We also get the aspect ratio of the image so that when we assign an image, it fits right into the canvas. The rest of the code clears the canvas and draws the new image into the canvas.

Function 2: Verify If The Photos Match By Sending Them To The API.

// Facesoft Face Match API Function
function verifyImages(image1, image2, callback){
  var params = {
    image1: image1,
    image2: image2,
  }
  var xhr = new XMLHttpRequest();
  xhr.open("POST", "https://api.facesoft.io/v1/face/match");
  xhr.setRequestHeader("apikey", apiKey);
  xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
  xhr.onload = function(){
    callback(xhr.response);
  }
  xhr.send(JSON.stringify(params));
}

In this function we make an XMLHttpRequest to the face match API endpoint. We’ve added the API key for authorisation and content type into the header. For the body we’re passing in an object containing the two images.

Now we’re done with functions :)

Upload Photo Button Click Event

// On Upload Photo Button Click
document.getElementById('upload').addEventListener('click', function(){
  imageUploadInput.click();
})

This click event listener for the upload button triggers a click for the image input.

Image Upload Input Change Event

// On Uploaded Photo Change
imageUploadInput.addEventListener('change', function(){
  // Get File Extension
  var ext = imageUploadInput.files[0]['name'].substring(imageUploadInput.files[0]['name'].lastIndexOf('.') + 1).toLowerCase();
  // If File Exists & Image
  if (imageUploadInput.files && imageUploadInput.files[0] && (ext == "png" || ext == "jpeg" || ext == "jpg")) {
    // Set Photo To Canvas
    var reader = new FileReader();
    reader.onload = function (e) {
      var img = new Image();
      img.src = event.target.result;
      img.onload = function() {
      setImageToCanvas(img, uploadedPhoto, uploadCanvas, uploadContext);
      }
    }
    reader.readAsDataURL(imageUploadInput.files[0]);
  }
})

In this change event listener, we retrieve the file extension and perform an if statement to check if there is an image file in the input. Then we use FileReader to load the image onto the canvas.

Take Photo Button Click Event

// On Take Photo Button Click
document.getElementById('capture').addEventListener('click', function(){
  setImageToCanvas(video, capturedPhoto, captureCanvas, captureContext, video.videoWidth, video.videoHeight);
})

This event listener now executes the set image to canvas to capture a still frame from the video and assign it into a canvas.

Verify Photo Button Click Event

// On Verify Photo Button Click
document.getElementById('verify').addEventListener('click', function(){
  // Remove Results & Alerts
  errorAlert.style.display = "none";
  warningAlert.style.display = "none";
  matchText.innerHTML = "";
  scoreText.innerHTML = "";
  // Get Base64
  var image1 = captureCanvas.toDataURL().split(',')[1];
  var image2 = uploadCanvas.toDataURL().split(',')[1]; 
  // Verify if images are of the same person
  verifyImages(image1, image2, function(response){
    if(response){
      var obj = JSON.parse(response);
      
      // If Warning Message
     
      if(obj.message){
        errorAlert.style.display = "none";
        warningAlert.style.display = "block";
        warningAlert.innerHTML = obj.message;
        matchText.innerHTML = "";
        scoreText.innerHTML = "";
      }
      // If Error
      else if(obj.error){
        errorAlert.style.display = "block";
        errorAlert.innerHTML = obj.error;
        warningAlert.style.display = "none";
        matchText.innerHTML = "";
        scoreText.innerHTML = "";
      }
      // If Valid
      else{
        errorAlert.style.display = "none";
        warningAlert.style.display = "none";
        matchText.innerHTML = obj.match;
        scoreText.innerHTML = (obj.score*100).toFixed(2)+"% Score";
      }
    }
  })
})

In this event, we first hide the error/warning alerts and remove any text from the match result and score percentage.

We then get the base64 of the images from the canvases and use the split method to only get the part without “ data:image/png;base64” so the API won’t return an error.

Lastly, we call the verify images function to send the data to the API and our response will be an object either containing the results, an error, or a message.

Final Code

// Set Default Images For Uploaded & Captured Photo
setImageToCanvas(uploadedPhoto, uploadedPhoto, uploadCanvas, uploadContext);
setImageToCanvas(capturedPhoto, capturedPhoto, captureCanvas, captureContext);

This will allow us to verify the default images by assigning them to their canvas.

5. The Rock vs Dwayne Johnson

If you click verify we shall now see if the API can tell the difference between The Rock at a young age and Dwayne Johnson we usually see in films…

The API correctly identifies the 2 as the same with a 96.53% match score!

Upload, Capture, Verify

In Closing

You should now be able to think of better, secure and more complex ways to implement face matching such as logging in, 2FA, authorisation, payments etc.

Accuracy & Reliability?

The results for the best face recognition algorithm in the world came out. The algorithm we’re using came in the top 10 beating Toshiba, Microsoft & VisionLabs, and came 2nd worldwide in the wild image test (detection at difficult angles).

Learn HTML5 Canvas Drawing with JavaScript

Learn HTML5 Canvas Drawing with JavaScript

Steps to Getting Started with The Canvas. Create the canvas element — give it an id, and a width/height (HTML) Add base styles — center the canvas, add a background color,

Let’s explore what the canvas is and draw some shapes.

Prerequisites / Info
  • This is part of the JS Game Dev Series
  • You should have some knowledge of JavaScript — I will not explain irrelevant syntax such as for-loops
  • Knowledge of ES6 Classes is helpful but not required
  • Basic math/geometry knowledge
  • Basic artistic skills
Starter Code

I moved this to a separate page to keep this article short and so I only have to update it in one place.

Final Code for this Tutorial

You can get all the code from this tutorial on the repository below. Keep in mind there’s also a lot of code included that’s not written here. This is because I added more code to create screenshots/diagrams for this tutorial.

Note: As the focus of this tutorial is not building a project, you don’t need to copy every line exactly. In fact, since we’ll be covering many examples, I encourage you to play with it and make a mess.

What is the Canvas Element?

Some quick bullet points to introduce you to the canvas.

  • Introduced with HTML version 5 to draw graphics using JavaScript
  • Graphics can be 2D or 3D and it’s able to use hardware acceleration
  • Used often today for creating games and visualizations (data or artistic)
Steps to Getting Started with The Canvas

When working with a canvas there are five steps to get started.

  1. Create the canvas element —give it an id, and a width/height (HTML)
  2. Add base styles — center the canvas, add a background color, etc (CSS)
  3. In JavaScript, get your canvas element by using the id
  4. Use the canvas element to get the context (your toolbox; more on it later)
  5. Use the context to draw

We’ll do steps one and two in HTML/CSS, but you could do it in JavaScript if you prefer.

Steps 1 and 2 for this project Our boilerplate / CodePen template already covered setting up the basic styles and adding a canvas element. For this project, I will change the canvas width/height to be 800x1200 to give us plenty of space.

// index.html
<canvas id="gameCanvas" width="800" height="1200"></canvas>

I also changed the canvas background to be white and added some margin to the bottom.

// styles.css
body {
  background: #111;
  color: #f8f8f8;
}
canvas {
  background: #f8f8f8;
  padding: 0;
  margin: 0 auto;
  margin-bottom: 1rem;
  display: block;
}

Steps 3 and 4 Get the canvas element by id, then use it to get the “2d” context.

// index.js
;(function () {
  const canvas = document.getElementById('gameCanvas')
  const ctx = canvas.getContext('2d')

})()

canvas-starter.js

grab the canvas element and create a 2D context

document.getElementById('gameCanvas') — searches for an HTML element that has the id of gameCanvas. Once it finds the element, we can then manipulate it with JavaScript.

canvas.getContext() — context is our toolbox of paintbrushes and shapes. The 2D context contains the set of tools we want. If you were working with 3D, you would use WebGL instead.

But wait what’s with the function thingy wrapping all of this?

This is an immediately invoked function expression (IIFE). We use it to prevent our code from leaking out in the global scope. This has several benefits such as preventing players (if this were a game) from accessing your variables directly and prevents your code from colliding with someone else's code (such as a library or another script on the website). The semicolon is there in case some other code is loaded before ours and it doesn’t have a semicolon at the end.

We’ll talk more about security in a future article, for now, let’s get to drawing stuff.

The Canvas Coordinate System

By default, the coordinate system starts at the top left. (X: 0, Y: 0) Moving down or to the right increases X and Y positions. You can play with the example below on this page.

a grid/coordinate project we’ll be creating

Quiz: The Canvas Element
  1. How do you select the canvas element in JavaScript?
  2. How do you get the context?
  3. Where is X: 0, Y: 0 on the canvas by default?
Simple Shapes

Let’s make use of the 2d context object to draw shapes. Feel free to reference the documentation page at any time.

There will also be a link to each method we use.

But wait for the DOM…

Before we draw anything, we want to make sure the DOM (HTML) finished loading to avoid any related errors. To do that, we will make a function to handle the setup process we did above and listen for the DOMContentLoaded event. We will call this function init (for initialize).

Remember: everything stays inside the IIFE wrapper. I won’t be showing it in the example code from now on. If you ever get lost refer to the completed project here.

// initialize config variables here
let canvas, ctx

// setup config variables and start the program
function init () {
  canvas = document.getElementById('gameCanvas')
  ctx = canvas.getContext('2d')
}

// wait for the HTML to load
document.addEventListener('DOMContentLoaded', init)

canvas-wait-for-dom.js

wait for DOM to load then run init function

We want our canvas and context variables to be available to all of our functions. This requires defining them up top and then giving them a value in the init function once the DOM loads. This completes our setup.

Note: A more scalable option is to accept the context variable as an argument to our drawing functions.

Rectangles / Squares

Let’s start by creating a square:

function init () {
  // set our config variables
  canvas = document.getElementById('gameCanvas')
  ctx = canvas.getContext('2d')

  // outlined square X: 50, Y: 35, width/height 50
  ctx.beginPath()
  ctx.strokeRect(50, 35, 50, 50)

  // filled square X: 125, Y: 35, width/height 50
  ctx.beginPath()
  ctx.fillRect(125, 35, 50, 50)
}

canvas-basic-rectangles.js

basic squares

Inside of our init function, we use context2D.beginPath to tell the canvas we want to start a new path/shape. On the next line, we create and draw a rectangle (a square in this case).

There are two different methods we use to draw the path to the screen:

ctx.strokeRect(x, y, width, height) — this creates a “stroked” rectangle. Stroke is the same thing as an outline or border

ctx.fillRect(x, y, width, height) — similar to strokeRect but this fills in the rectangle with a color

The Result:

stroked square and filled square

There are a few things to note here:

  1. The colors default to black stroke and black fill.
  2. The origin point or X: 0, Y: 0 for these shapes are at their top left, similar to the canvas.
  3. I just picked a random x, y for the first square and then added 50 + 50+ 25 (previous square X + previous square width + 25px margin) for the x position.


positioning the squares

What if we want to change the color/style? Let’s add a red outlined square that’s also filled with blue.

Position first:

  • X = 200 previous square width + previous position + 25px margin = 50 + 125 + 25
  • Y = 35 We will keep it in the same row
  • The size will be the same (50 x 50)
ctx.beginPath()
ctx.strokeRect(200, 35, 50, 50) // plugging in our new position

But wait… we want a fill AND a stroke, does this mean we have to draw two squares? You can draw two squares but we will make use of several other methods instead.

// inside the init function

// filled, outlined square X: 200, Y: 35, width/height 50
ctx.beginPath()
ctx.strokeStyle = 'red'
ctx.fillStyle = 'blue'
ctx.lineWidth = 5
ctx.rect(200, 35, 50, 50)
ctx.fill()
ctx.stroke()

stroke-filled-square.js

create an outline and filled in square

The Result:

a third colorful square

ctx.rect(x, y, width, height) — this is like the other two rectangle methods, but it does not immediately draw it. It creates a path for the square in memory, we then configure the stroke, fill, and stroke width before calling ctx.fill and/or ctx.stroke to draw it on screen

ctx.strokeStyle = ‘any valid css color’ — sets the outline/stroke color to any string that works in CSS. i.e. ‘blue’, ‘rgba(200, 200, 150, 0.5)’, etc

ctx.fillStyle = ‘any valid css color’ — same as above but for the fill

ctx.lineWidth = number — sets the stroke width

ctx.fill() — fills the current path

ctx.stroke() — strokes the current path

Drawing any shape always follows these steps:

  1. Set the styles — optional and can be set any time before rendering
  2. Begin the path — start creating the virtual path (not drawn to screen yet)
  3. Use the path functions to create a shape — i.e. the rect method
  4. Draw the path to the screen — using fill or stroke

Note: We did not need to use the _ctx.rect()_ function just to change the colors, we used it because we wanted both a stroke and a fill. You can just as easily set _ctx.fillStyle_ and use _ctx.fillRect()_

Setting the fill or stroke style will cause any shapes created after, to have the same style. For example, if we add a fourth square using the code below it would have the same style as the third square.

// 4th square, uses the same style defined previously
ctx.beginPath()
ctx.rect(275, 35, 50, 50)
ctx.fill()
ctx.stroke()

Result:

4th square, oops same style

Anytime you want to add a fill/stroke to your shapes, explicitly define the styles.

Optimizing our Code with Classes

Making use of classes we can create a robust Rectangle object and clean up our code.

Classes are functions that create Objects. We want to create Rectangle objects that contain information about themselves, such as their position, styles, area, and dimensions.

I won’t go into much detail on classes as it’s not required and you can get by with normal functions. Check the MDN documentation page on classes to learn more about them.

// ( still inside the IIFE )

// function to create rectangle objects
class Rectangle {
  // you create new Rectangles by calling this as a function
  // these are the arguments you pass in
  // add default values to avoid errors on empty arguments
  constructor (
    x = 0, y = 0,
    width = 0, height = 0,
    fillColor = '', strokeColor = '', strokeWidth = 2
  ) {
    // ensure the arguments passed in are numbers
    // a bit overkill for this tutorial
    this.x = Number(x)
    this.y = Number(y)
    this.width = Number(width)
    this.height = Number(height)
    this.fillColor = fillColor
    this.strokeColor = strokeColor
    this.strokeWidth = strokeWidth
  }

  // get keyword causes this method to be called
  // when you use myRectangle.area
  get area () {
    return this.width * this.height
  }

  // gets the X position of the left side
  get left () {
    // origin is at top left so just return x
    return this.x
  }

  // get X position of right side
  get right () {
    // x is left position + the width to get end point
    return this.x + this.width
  }

  // get the Y position of top side
  get top () {
    // origin is at top left so just return y
    return this.y
  }

  // get Y position at bottom
  get bottom () {
    return this.y + this.height
  }

  // draw rectangle to screen
  draw () {
    // destructuring
    const {
      x, y, width, height,
      fillColor, strokeColor, strokeWidth
    } = this

    // saves the current styles set elsewhere
    // to avoid overwriting them
    ctx.save()

    // set the styles for this shape
    ctx.fillStyle = fillColor
    ctx.lineWidth = strokeWidth

    // create the *path*
    ctx.beginPath()
    ctx.strokeStyle = strokeColor
    ctx.rect(x, y, width, height)

    // draw the path to screen
    ctx.fill()
    ctx.stroke()

    // restores the styles from earlier
    // preventing the colors used here
    // from polluting other drawings
    ctx.restore()
  }
}

rectangle-class.js

rectangle class

Classes are optional and if the syntax confuses you, then just think of it as an object with methods and properties. Classes aside, two more canvas functions were introduced in the draw method:

ctx.save() — saves the current styles

ctx.restore() — restores the last saved styles

We use these methods to prevent the issue we saw with the fourth square that had unexpected colors.

Canvas stores styles on a stack structure. When we call ctx.save() it pushes the current styles onto the stack and calling ctx.restore() pops it off the stack.


style stack animated

I only saved one set of styles in this animation but you can save as many times as you want and restore the most recent styles. Note that saving does not reset the current styles.

Styles include:
strokeStyle, fillStyle, globalAlpha, lineWidth, lineCap, lineJoin, miterLimit, lineDashOffset, shadowOffsetX, shadowOffsetY, shadowBlur, shadowColor, globalCompositeOperation, font, textAlign, textBaseline, direction, imageSmoothingEnabled
— MDN

We can now start putting this Rectangle class to use:

// create a new rectangle object using the Rectangle class
const mySquare = new Rectangle(400, 85, 50, 50, 'gold')

// now we have data and methods to describe our square
console.log(mySquare)
// Object
// fillColor: "gold"
// height: 50
// strokeColor: ""
// strokeWidth: 2
// width: 50
// x: 450
// y: 100
// area: (...)
// bottom: (...)
// left: (...)
// right: (...)
// top: (...)

// draw the square data to screen
mySquare.draw()

using-rectangle-class.js

create a new square using Rectangle class

The Result:


square drawing from rectangle class

Note: I added a grid for the screenshots. We’ll be making a grid at the end of this section.

We can keep reusing the class to make more squares/rectangles:


// mySquare from earlier...
// const mySquare = new Rectangle(400, 85, 50, 50, 'gold')

// lets use the helper methods to
// draw shapes on the sides of mySquare
const childrenSquares = [
  // top side square - align x with mySquare's left side
  // align bottom with top of mySquare
  new Rectangle(mySquare.left, mySquare.top - 50, 50, 50, 'red'),

  // right side square - align x with right side of mySquare
  // align top with mySquare top
  new Rectangle(mySquare.right, mySquare.top, 50, 50, 'green'),

  // bottom square
  new Rectangle(mySquare.left, mySquare.bottom, 50, 50, 'blue'),

  // left square
  new Rectangle(mySquare.left - 50, mySquare.top, 50, 50, 'magenta')
]

// draw all of the child squares by looping over them
childrenSquares.forEach(square => square.draw())

children-squares.js

child squares nonsense

We create an array and populate it with new Rectangles positioned based on the mySquare object created earlier. Then we loop over the array and call the draw method on every square.

What do we get from all that code?

child squares?

Well… it’s something.

I know this is all boring and tedious but we’ve covered the basics of canvas and you’ve at least seen what a class looks like now. Let’s finish creating more shapes. (it’ll go quicker from now on I promise)

Lines 🔗

Rectangles are the only pre-defined shape with canvas, we create other shapes on our own. We can use lines to build the foundation of these shapes.

// LINES

// save previous styles & set our current styles
ctx.save()
ctx.strokeStyle = 'blue'
ctx.fillStyle = 'blue'
ctx.lineWidth = 4

// stroked trapezoid
ctx.beginPath()
ctx.moveTo(50, 200) // sets our starting point
ctx.lineTo(100, 200) // create a line from start point to X: 100, Y: 200
ctx.lineTo(90, 180) // create the right side
ctx.lineTo(60, 180) // top side
ctx.closePath() // left side and closes the path
ctx.stroke() // draws it to screen via a stroke

// filled trapezoid
ctx.beginPath()
ctx.moveTo(150, 200) // starting point
ctx.lineTo(200, 200) // bottom side
ctx.lineTo(190, 180) // right side
ctx.lineTo(160, 180) // top side
// no need to closePath, fill automatically closes the path
ctx.fill()

// restore saved styles (for other examples)
ctx.restore()

lines-trapezoids.js

using lines to make trapezoid-like shapes

The Result:

trapezoid things

New Methods:

ctx.moveTo(x, y) — you can think of this as moving our virtual “pen”, we use it to set the starting point for the first line

ctx.lineTo(x, y) — creates a line to X, Y; the starting point is the last position of our “pen”. This allows us to start new lines at the endpoint of previous lines.

ctx.closePath() — when using a stroke we need to call this to draw the final line and close the path. Fill will automatically close the path

Note: If you need curved lines then you can use Bézier curves with the quadratic or cubic bézier curve functions. I’ll cover them in another tutorial to keep this one from becoming too long.

Text 🔤

If you ever worked with any kind of text editor similar to Microsoft Word or any of Adobe’s tools, then these options will be familiar to you.

// TEXT

// usual setup
ctx.save()
ctx.strokeStyle = 'red'
ctx.fillStyle = 'black'

// text specific styles
ctx.font = 'bold 16px Monospace'
ctx.textAlign = 'left'
ctx.textBaseline = 'alphabetic'

// draw stroked text to screen
ctx.strokeText('Stroked Text', 50, 250)

// calculate the width of this text using current font/styles
const textWidth = ctx.measureText('Stroked Text').width

// X = previous X position + width + 25px margin
ctx.fillText('Filled Text', 50 + textWidth + 25, 250)

ctx.restore()

canvas-text.js

ctx.strokeText(text, x, y) — creates the text path and strokes it

ctx.fillText(text, x, y) — same as above but fills the text

ctx.font(CSSFontString) — set the font using the CSS font format

ctx.measureText(text) — performs some calculations using the current styles and returns an object with the results, including the calculated width

The rest of the options are self-explanatory or require knowledge of font design, which is outside the scope of this tutorial.

Circles & Partial Circles (arcs) 🔴
// ARCS / Circles
// usual setup
ctx.save()
ctx.strokeStyle = 'black'
ctx.fillStyle = 'red'

// x, y, radius, startAngle, endAngle, antiClockwise = false by default
ctx.beginPath()
ctx.arc(50, 300, 15, 0, 2 * Math.PI, false) // full circle
ctx.fill()
ctx.stroke()

// half circle counter clockwise
ctx.beginPath()
ctx.arc(100, 300, 15, 0, Math.PI, true)
ctx.fill()
ctx.stroke()

// half circle clockwise
ctx.beginPath()
ctx.arc(150, 300, 15, 0, Math.PI)
ctx.fill()
ctx.stroke()

// pacman like
ctx.beginPath()
ctx.fillStyle = 'gold'
ctx.arc(200, 300, 15, 0.1 * Math.PI, 1.85 * Math.PI)
ctx.lineTo(200, 300)
ctx.fill()

ctx.restore()

canvas-arcs.js

circles / arcs code

resulting circles/arcs

The only new function here is the arc method.

arc(x, y, radius, startAngle, endAngle, antiClockwise)

X, Y — defines the position of the center point, not the top left

radius — the size of the circle/arc

startAngle, endAngle — I think these are self-explanatory but it’s important to note that these angles are in Radians not degrees.

Math Aside: 1π (Pi) radians is equal to half a circle, 2π gives you a full circle.
Watch this video for more on the math of a circle

Triangles 🔺

As there are no triangle functions, we have to make them ourselves using lines.

// TRIANGLES
// usual setup
ctx.save()
ctx.strokeStyle = 'black'
ctx.fillStyle = 'orangered'

// Filled Triangle
ctx.beginPath()
ctx.moveTo(50, 400) // starting point
ctx.lineTo(50, 350) // left side
ctx.lineTo(100, 400) // hypotenuse / long side
ctx.fill() // closes the bottom side & fills

// stroked triangle
ctx.beginPath()
ctx.moveTo(150, 400) // starting point
ctx.lineTo(200, 400) // bottom side
ctx.lineTo(200, 350) // right side
ctx.closePath() // hypotenuse/long side (remember to close path for strokes!)
ctx.stroke()

ctx.restore()

canvas-triangle.js

Nothing new here. Refer to the sections above if you’re lost. (or ask in the comments)

Quiz: Basic Shapes
  1. What arguments does the rect(_, _, _, _) function take?
  2. After you’ve used the rect function, what two methods can draw the rectangle to the screen? (the same functions for any path)
  3. What function can create circles?
  4. What two properties can we set to change the fill and outline styles?
  5. How do you set the starting position when using lineTo(x,y)

Answers: (links to related MDN pages)

  1. Rect function docs
  2. Drawing method 1, drawing method 2
  3. Function to draw circles
  4. strokeStyle, fillStyle
  5. ctx.moveTo(x,y)
Challenge: Visualize the Canvas Coordinate System

Use what you learned to draw a coordinate plane or grid with X and Y starting at the top left and end where the canvas ends.

Examples

Tips

  • Use for loops to create multiple lines
  • It can be a full grid, just text, or lines with tick marks... Make the grid you will want to use
  • As we haven’t covered animation yet, don’t worry about animating it. The example above was animated only for demonstration purposes.

Solution Don’t worry if you didn’t solve it, this one is challenging.

I started by making a new JS file and loading it instead of the example shapes from earlier.

<!-- index.html -->
<!-- <script src="js/index.js"></script> -->
<script src="js/gridSolution.js"></script>

Add the initial setup to your new JS file.

// gridSolution.js

;(function () {
  let canvas, ctx
  
  function init () {
    // set our config variables
    canvas = document.getElementById('gameCanvas')
    ctx = canvas.getContext('2d')
  }
  
  document.addEventListener('DOMContentLoaded', init)
})()

gridSolution-initial.js

initial setup for the grid solution

Now, decide if you want to make a reusable Grid class or create something simpler. I will keep it simple for this example solution by using only one function.

// draws a grid
function createGrid () {
  // draw a line every *step* pixels
  const step = 25

  // our end points
  const width = canvas.width
  const height = canvas.height

  // set our styles
  ctx.save()
  ctx.strokeStyle = 'gray' // line colors
  ctx.fillStyle = 'black' // text color

  // draw vertical from X to Height
  for (let x = 0; x < width; x += step) {

  }

  // draw horizontal from Y to Width
  for (let y = 0; y < height; y += step) {

  }

  // restore the styles from before this function was called
  ctx.restore()
}

function init () {
  // set our config variables
  canvas = document.getElementById('gameCanvas')
  ctx = canvas.getContext('2d')

  createGrid()
}

createGrid-starter.js

partial grid solution

Look at the above code, then try to fill in the blanks yourself if you haven’t already solved it. The next snippet will be the complete code.


example solution result

// GRID CHALLENGE SOLUTION

;(function () {
  let canvas, ctx

  // draws a grid
  function createGrid () {
    // draw a line every *step* pixels
    const step = 50

    // our end points
    const width = canvas.width
    const height = canvas.height

    // set our styles
    ctx.save()
    ctx.strokeStyle = 'gray' // line colors
    ctx.fillStyle = 'black' // text color
    ctx.font = '14px Monospace'
    ctx.lineWidth = 0.35

    // draw vertical from X to Height
    for (let x = 0; x < width; x += step) {
      // draw vertical line
      ctx.beginPath()
      ctx.moveTo(x, 0)
      ctx.lineTo(x, height)
      ctx.stroke()

      // draw text
      ctx.fillText(x, x, 12)
    }

    // draw horizontal from Y to Width
    for (let y = 0; y < height; y += step) {
      // draw horizontal line
      ctx.beginPath()
      ctx.moveTo(0, y)
      ctx.lineTo(width, y)
      ctx.stroke()

      // draw text
      ctx.fillText(y, 0, y)
    }

    // restore the styles from before this function was called
    ctx.restore()
  }

  function init () {
    // set our config variables
    canvas = document.getElementById('gameCanvas')
    ctx = canvas.getContext('2d')

    createGrid()
  }

  document.addEventListener('DOMContentLoaded', init)
})()

grid-example-final-solution.js

final example grid code

Feel free to tweak your grid and save it for future use. I saved the animated one as an NPM package to use with upcoming tutorials.

Final Challenge: Draw Some Art

Now it’s time to put everything you’ve learned to use, here’s your challenge:

Draw a picture using a combination of the shapes we learned. Find some reference images or make something up.

Ideas

  • Emojis / Faces
  • Flags (Japan’s flag? 😂)
  • 2D Game/Cartoon Characters
  • Logos
  • Charts (bar chart, pie chart, etc) — a little more advanced and I’ll be doing another tutorial on charts but if you want to try it on your own go for it.
  • Landscape — draw a house, some grass, a sun or perhaps a starry night sky
  • Search for examples on CodePen to get ideas (prepare to be overwhelmed by the crazy art some people make)

Tips

  • Use canvas.height / 2 and canvas.width / 2 to get the center X, Y of the canvas
  • If you did the grid challenge from earlier, now is a good time to use it
  • If your drawing needs a lot of curves, look into the bezier curve functions: quadraticCurveTo and bezierCurveTo
  • Try finding some examples on CodePen
  • Keep it simple. This challenge is just to practice drawing shapes on the canvas, not to create some complex game character.

When you finish share a link to your CodePen / GitHub repository in the comments.

Reflection

What did you struggle with the most? Or was everything a cakewalk? What could have been different? I would love to hear your feedback in the comments. Otherwise, note what you struggled with and spend more time researching and reviewing that topic.

Learn HTML5 Canvas - DRAW - HTML & JavaScript

Learn HTML5 Canvas - DRAW - HTML & JavaScript

We go over the basics of the HTML5 Canvas element and use JavaScript to draw lines, circles, squares and rectangles to the DOMs Canvas. JavaScript combined with HTML5 Canvas can be used to draw elements anywhere you want inside of the HTML5 Canvas. We learn the basics in a simple how to video but in the next part we will look how to animate the HTML5 Canvas using JavaScript to change the X & Y coordinates of shapes we create. We will follow an Object Oriented Programming pattern.

Top 7 JavaScript Projects on GitHub

Top 7 JavaScript Projects on GitHub

Top 7 JavaScript Projects on GitHub. A progressive, incrementally-adoptable JavaScript framework for building UI on the web. Read on to find your next favorite framework!

JavaScript was originally known only for developing the client side of web pages, and as new frameworks have been developed for server-side purposes, it is no surprise that JavaScript has become one of the most popular programming languages in the world today.

With the increase in the number of programmers learning to code in JavaScript, the development of great projects has been on the rise as well.

1. React.js

JavaScript is known mainly for client-side projects and React.js is an example of a framework for developing great front-end designs and interactions. Created by Facebook, React is a library that is used for creating powerful reusable UI components.

One of the positives of using React is that it hides away complexity by using a virtual DOM which helps improve applications' performance. Features of React include the JavaScript syntax extension, unidirectional data flow, components, and much more.

Learning React is pretty easy if you have a good grasp of JavaScript. You can access the tutorial from the React.js website. Installation and setup of React is pretty easy.

npm install -g create-react-app

create-react-app my-app

cd my-app

npm start 

2. Vue.js

Just like React, Vue is another framework for building lovely user interfaces. This progressive framework is designed to be easily adaptable as time passes, this makes the library easy to integrate with other projects and use anytime.

Vue.js is known widely for its simplicity and, besides that, it is lightweight, well documented, and allows for flexibility during development. Vue encourages developers to write "simple JavaScript," therefore, it is easy for beginners to pick up.

Looking for a guide? Here is one from the developers themselves. Vue is pretty easy to install and setup.

_npm install -g vue-cli_

_vue init webpack my-app_

_cd my-app_

_npm install_

_npm run dev_

3. Node.js

Here is one of the best ever frameworks for server-side development, and the which gave JavaScript its popularity with server-side scripting projects.

Node.js has brought about the package management tool NPM which has helped make life easier for lots of developers. Developers also love that it provides a non-blocking I/O model, can be used to develop real-time web applications, is easy to learn, and has a large community.

The installation process for Node is different on Windows and Linux. For Windows, a simple download and install of the Node.js executable application would suffice.

For Linux, the following Linux terminal command would get it installed:

sudo apt-get update

sudo apt-get install nodejs

After installation, the following command should be run to confirm a successful installation.

node -v

4. HTML5

The development of web pages has become more complicated over time. With productivity at stake, reduction of routine tasks is of high importance.

With the HTML5 Boilerplate project, development becomes a more enjoyable process. This is the most popular frontend boilerplate framework you will find, as it helps build fast, robust and adaptable web applications.

It includes Normalize.css, jQuery, a custom build of the Modernizr face detection library, and provides high performance to top it all off.

The HTML5 Boilerplate framework can be downloaded from their GitHub page.

5. Three.js

There are a few 3D computer graphics frameworks, and Three.js is one of them. Three.js is used to create beautiful 3D computer graphics in web browsers by utilizing the WebGL engine.

Three.js comes with a bunch of features. Features such as effects and scenes, camera, animations such as skinned mesh and morph blend mesh, lights, etc. have helped it gain popularity.

Its large community of developers and users is an immense positive, so you can expect stable improvements on this project.

Three.js is easy to install and can be downloaded from the GitHub page.

6. MeteorJS

In terms of frameworks for building applications for all platforms, MeteorJS is one of the best you will ever find.

MeteorJS allows for real-time web development, makes for easy development of the client side, server side, and the database of applications much easier, it is easy to code in and pick up for beginners, and also has a huge developer community.

Looking for a guide? Here is one written by the developers of Meteor.

Meteor is easily installed, and running the terminal command below will do the job.

sudo curl https://install.meteor.com/ | sh

To check if the installation was successful, use the command below:

meteor --version

7. Express.js

Earlier in the article, we talked about the Node.js framework. Express was actually built upon Node.js!

Express.js is a flexible Node.js-based web application framework used for developing quality web and mobile applications.

Used for building web applications and APIs, Express.js has become very popular in the JavaScript community. If you have been in the business for a while, you most likely would have heard of the MEAN stack - Express makes up the backend part of that stack.

Express makes the development process faster, it's easy to configure and customize, can be integrated with a ton of template engines, and doesn't make a connection to databases a hassle.

Since Express is built on Node.js, it can be installed using the NPM tool.

npm init

Then to install and add Express to the list of dependencies:

npm install express --save

Or to install without adding Express to the list of dependencies:

npm install express --no-save

What project do you think should have made the list? What project do you use the most? Let us know your views.

Thank for reading !