How To Capture Photo Using Webcam In jQuery/JavaScript

In this article, we will learn how to capture a photo using a webcam or device’s camera in jQuery/JavaScript.

For a better user interface, the capture photo feature is an interesting feature in modern websites and that can be used for many purposes like uploading photo(s) to the server, etc.

Let’s first use HTML code where the user can see their live video and capture his/her photo. We have used jQuery CDN to make it much easier to use JavaScript.

Now create and open the Index.html file and add the code to it.

<!DOCTYPE html>
        .d-none {
            display: none;
    <button type="button" id="btnActivateCamera">Activate Camera</button>
    <button type="button" id="btnDeactivateCamera" class="d-none">Deactivate Camera</button>
    <br />
    <video id="capturevideo" width="230" height="230" class="d-none"></video>
    <br />
    <button type="button" id="btnCapture" class="d-none">Capture</button>
    <hr />
    <canvas id="capturecanvas" width="230" height="230" class="d-none"></canvas>
    <script src=""></script>
    <script src="index.js"></script>

Now create and open the Index.js file and add the code to it.

var videoCapture;
$(document).ready(function () {
    videoCapture = document.getElementById('capturevideo');
$(document).on('click', '#btnActivateCamera', function () {
    if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
        // access video stream from webcam
        navigator.mediaDevices.getUserMedia({ video: true }).then(function (stream) {
            // on success, stream it in video tag 
            window.localStream = stream;
            videoCapture.srcObject = stream;
        }).catch(e => {
            // on failure/error, alert message. 
            alert("Please Allow: Use Your Camera!");
$(document).on('click', '#btnDeactivateCamera', function () {
    // stop video streaming if any
    localStream.getTracks().forEach(function (track) {
        if (track.readyState == 'live' && track.kind === 'video') {
$(document).on('click', '#btnCapture', function () {
    document.getElementById('capturecanvas').getContext('2d').drawImage(videoCapture, 0, 0, 230, 230);
function activateCamera() {
function deactivateCamera() {


Please give your valuable feedback and if you have any questions or issues about this article, please let me know.

Also, check Allow CORS Requests From Any Origin In .NET Core

1 Comment

  1. Eddy Erkelens

    This code doesnt work on iPad (gen 1)?
    Is there something I can change, so it will?


Submit a Comment

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


Select Categories