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

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:

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

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:

  • 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.

Top comments (1)

Collapse
 
undqurek profile image
undqurek

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