How to Capture Photos With Webcam In Javascript

Welcome to a tutorial on how to capture photos with a webcam in Javascript. Yes, the Stone Age of the Internet is long over, and it is totally possible to take photos straight from using Javascript… Although it is not so straightforward and requires quite a bit of coding. Just how do we do it? Read on to find out!

ⓘ I have included a zip file with all the example source code at the start of this tutorial, so you don’t have to copy-paste everything… Or if you just want to dive straight in.

 

 

QUICK SLIDES

 

TABLE OF CONTENTS

Download & Notes JS Webcam Useful Bits & Links
The End

 

DOWNLOAD & NOTES

Firstly, here is the download link to the example code as promised.

 

QUICK NOTES

  • Launch webcam.html in your browser, take note to use http:// and not file://.
If you spot a bug, feel free to comment below. I try to answer short questions too, but it is one person versus the entire world… If you need answers urgently, please check out my list of websites to get help with programming.

 

 

EXAMPLE CODE DOWNLOAD

Click here to download the source code, I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

 

 

JAVASCRIPT WEBCAM CAPTURE

All right, let us now get into the steps and examples of how to take a photo with Javascript.

 

STEP 1) THE HTML

webcam.html
<!-- (A) VIDEO LIVE FEED -->
<video id="kam-live" autoplay></video>
 
<!-- (B) SNAPSHOTS -->
<div id="kam-snaps"></div>
 
<!-- (C) CONTROLS -->
<div id="kam-controls">
  <button id="kam-take" disabled>
    <span class="material-icons">photo_camera</span>
  </button>
  <button id="kam-save" disabled>
    <span class="material-icons">save</span>
  </button>
</div>

Just a simple HTML interface with only a few components:

  1. <video id="kam-live"> is where we will “live stream” the feed from the webcam.
  2. <div id="kam-snaps"> where we place the snapshots.
  3. “Captain Obvious” buttons.
    • <button id="kam-take"> Takes a picture, directly insert it into the HTML page
    • <input id="vid-save"> Take a picture and offer a “save as”.

 

 

STEP 2) INITIALIZE WEBCAM

stream.js
// (A) INITIALIZE
hVid : null, hSnaps :null, hTake : null, hSave : null,
init : () => {
  // (A1) GET HTML ELEMENTS
  webkam.hVid = document.getElementById("kam-live"),
  webkam.hSnaps = document.getElementById("kam-snaps"),
  webkam.hTake = document.getElementById("kam-take"),
  webkam.hSave = document.getElementById("kam-save");
 
  // (A2) GET USER PERMISSION TO ACCESS CAMERA
  navigator.mediaDevices.getUserMedia({ video: true })
  .then((stream) => {
    // "LIVE FEED" WEB CAM TO <VIDEO>
    webkam.hVid.srcObject = stream;
 
    // ENABLE BUTTONS
    webkam.hTake.onclick = webkam.take;
    webkam.hSave.onclick = webkam.save;
    webkam.hTake.disabled = false;
    webkam.hSave.disabled = false;
  })
  .catch((err) => { console.error(err); });
}
window.addEventListener("load", webkam.init);

On window load, webkam.init() will fire up to initialize the app.

  • (A1) Self-explanatory. Get the HTML elements.
  • (A2) We cannot directly access the webcam and have to ask the user for permission – navigator.mediaDevices.getUserMedia({ video : true })
  • (A2) On getting access permission, we simply set the webcam stream into the HTML video – webkam.hVid.srcObject = stream;
  • (A2) Lastly, enable all the controls when ready.

Please take note – getUserMedia() requires https:// to work properly, http://localhost is an exception for testing. Also, if the user denies permission, getUserMedia() will not prompt anymore. You will have to serve your own “how to manually give permission” notice in catch().

 

 

STEP 3) SNAPSHOT TO HTML CANVAS

stream.js
// (B) HELPER - SNAP VIDEO FRAME TO CANVAS
snap : () => {
  // (B1) CREATE NEW CANVAS
  let canvas = document.createElement("canvas"),
      ctx = canvas.getContext("2d"),
      vWidth = webkam.hVid.videoWidth,
      vHeight = webkam.hVid.videoHeight;
 
  // (B2) CAPTURE VIDEO FRAME TO CANVAS
  canvas.width = vWidth;
  canvas.height = vHeight;
  ctx.drawImage(webkam.hVid, 0, 0, vWidth, vHeight);
 
  // (B3) DONE
  return canvas;
},
 
 // (C) TAKE A SNAPSHOT - PUT CANVAS INTO <DIV> WRAPPER
take : () => {
  webkam.hSnaps.appendChild(webkam.snap());
},

So just how can we capture a snapshot?

  • Basically, create an HTML canvas – canvas = document.createElement("canvas");
  • Then, get the 2D context – ctx = canvas.getContext("2d");
  • Draw the current video frame onto the canvas – ctx.drawImage(VIDEO, 0, 0, VID-WIDTH, VID-HEIGHT);

That’s all for the “difficult snapshot”.

 

STEP 4) DOWNLOAD SNAPSHOT

stream.js
// (D) SAVE SNAPSHOT
save : () => {
  // (D1) TAKE A SNAPSHOT, CREATE DOWNLOAD LINK
  let canvas = webkam.snap(),
      anchor = document.createElement("a");
  anchor.href = canvas.toDataURL("image/png");
  anchor.download = "snap.png";
 
  // (D2) "FORCE DOWNLOAD" - MAY NOT ALWAYS WORK!
  anchor.click();
  anchor.remove();
  canvas.remove();
 
  // (D3) SAFER - LET USERS MANUAL CLICK
  // anchor.appendChild(canvas);
  // webkam.hSnaps.appendChild(anchor);
}

Attaching the snapshot to the HTML page may not be the productive thing to do, so here’s how we can download it.

  • Create an HTML anchor link – anchor = document.createElement("a").
  • Attach the canvas data URL onto the anchor tag – anchor.src = canvas.toDataURL("image/png").
  • Finally, a neat trick is to anchor.click() to offer a “save as”. But take note, this will not always work due to security constraints.
  • The safer way is to attach the link to the HTML page itself, let the user click to download manually.

 

 

EXTRA) UPLOAD THE SNAPSHOT

// (A) GET SNAPSHOT CANVAS
var canvas = webkam.snap();
 
// (B) CONVERT TO BLOB + UPLOAD
canvas.toBlob((blob) => {
  let file = new File([blob], "demo.png", { type: "image/png" });
  var data = new FormData();
  data.append("up", file);
  fetch("SERVER.SCRIPT", { method:"POST", body:data });
});

If we can save the canvas as a file, we can also upload it to the server. Just convert it into a blob, into an image file, and upload accordingly.

 

USEFUL BITS & LINKS

That’s all for this project, and here is a small section on some extras and links that may be useful to you.

 

COMPATIBILITY CHECKS

Works well on all “Grade A” major browsers.

 

LINKS & REFERENCES

 

INFOGRAPHIC CHEAT SHEET

Capture Photos With Webcam In Javascript (click to enlarge)

 

THE END

Thank you for reading, and we have come to the end of this guide. I hope that it has helped you with your project, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!

3 thoughts on “How to Capture Photos With Webcam In Javascript”

  1. Nishal Beegamudre

    Can you please send the code such that the captured screenshot can be shown on one part of the html page as soon as screenshot button will be clicked?

Leave a Comment

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