DEV Community

Cover image for Display web camera on canvas element
EneasLari
EneasLari

Posted on • Edited on

Display web camera on canvas element

Lets view the video stream from web camera on canvas so we can benefit from canvas capabilities (text on video ,add filters and more).

Basic html

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Bootstrap CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<title>Video on canvas</title>
</head>
<body>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script>
</body>
</html>
view raw index_1.html hosted with ❤ by GitHub

Create a javascript file index.js and add a reference to the html at line 15:

<script src="index.js"></script>
Enter fullscreen mode Exit fullscreen mode

Next we will create a video element which will be hidden because we want to view the canvas element:

<video autoplay playsinline webkit-playsinline muted hidden id="videoelement"></video>
Enter fullscreen mode Exit fullscreen mode

Now lets add a canvas element inside a bootstrap container:

    <div class="container">
        <canvas id="canvaselement" width="1920" height="1080"></canvas>
    </div>

Enter fullscreen mode Exit fullscreen mode

The final html:

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Bootstrap CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<title>Video on canvas</title>
</head>
<body>
<video autoplay playsinline webkit-playsinline muted hidden id="videoelement"></video>
<div class="container">
<canvas id="canvaselement" width="1920" height="1080"></canvas>
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script>
</body>
</html>
view raw index.html hosted with ❤ by GitHub

Now that we have a bootstrap html template lets add javascript:

var videoelement = document.getElementById("videoelement");
var localStreamConstraints = {
audio: true,
video: { width: 1920, height: 1080 },
};
if (videoelement) {
navigator.mediaDevices
.getUserMedia(localStreamConstraints)
.then(gotStream)
.catch(function (e) {
if (confirm("An error with camera occured:(" + e.name + ") Do you want to reload?")) {
location.reload();
}
});
}
//if found stream found
function gotStream(stream) {
videoelement.srcObject = stream
}
view raw index_1.js hosted with ❤ by GitHub

Code explanation

  • At line 9 we prompt the user for permission to use camera and microphone

  • If the user accepts then at line 10 the gotStream function is executed.

  • gotStream add as source of video the stream of camera and microphone

  • If the user denies the permission or stream is inaccessible then at line 11 we prompt the user to reload the page in order to try again

Now that we added the video element and we set the stream of camera to the video element lets add a canvas that will display frames of video:

var videoelement = document.getElementById("videoelement");
var streamContraints = {
audio: true,
video: { width: 1920, height: 1080 },
};
var canvaselement = document.querySelector('#canvaselement');
var ctx = canvaselement.getContext('2d', { alpha: false });
var canvasInterval = null;
var fps=60
if (videoelement) {
navigator.mediaDevices
.getUserMedia(streamContraints)
.then(gotStream)
.catch(function (e) {
if (confirm("An error with camera occured:(" + e.name + ") Do you want to reload?")) {
location.reload();
}
});
}
//if stream found
function gotStream(stream) {
videoelement.srcObject = stream
videoelement.play()
}
function drawImage(video) {
ctx.drawImage(video, 0, 0, canvaselement.width, canvaselement.height);
}
canvasInterval = window.setInterval(() => {
drawImage(videoelement);
}, 1000 / fps);
view raw index.js hosted with ❤ by GitHub
  • At line 30 we draw at canvas context an image

  • At line we call 32 we call window.setInterval to draw a frame of video every 1000/60 milliseconds

In the next article we will add filters, texts and we will edit video

Source Code

Thanks for your time.
Leave a question or comment below.

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

Top comments (1)

Collapse
 
undqurek profile image
undqurek

Another nice solution: dirask.com/posts/JavaScript-play-c...

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more