Webcam displayed twice

Hi guys

I am doing a project using the built-in camera. So I prepared the same code for both boxes (A and B) but when the website opens the camera is displayed only in the A box. Is there a way to display it in the B box as well?

Thanks a lot (53.9 KB)

PS: Here is the javascript code for the box:

<video autoplay="" id="vid" width="244" height="211" style="display: inline;"></video>
<canvas id="canvas" width="244" height="211"></canvas>
<script type="text/javascript">
var video = document.querySelector("#vid");
        var canvas = document.querySelector('#canvas');
        var ctx = canvas.getContext('2d');
        var localMediaStream = null;
        var onCameraFail = function (e) {
            console.log('Camera did not work.', e);
        function snapshot() {
            if (localMediaStream) {
                ctx.drawImage(video, 0, 0);
        navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
        window.URL = window.URL || window.webkitURL;
navigator.getUserMedia({video:true}, function (stream) {
            video.src = video.mozSrcObject = stream;
            localMediaStream = stream;
        }, onCameraFail);

I’m not sure what the correct code is for this, but there’s a few things fundamentally wrong:

  • you have the same code duplicated in two elements. Since you’re relying on ids for identification, you will have overlap and won’t be able to talk to different video/canvas elements. You’ll want to give them different IDs.

  • you are not doing anything with the snapshot() function, which seems to be the heart of drawing into a different view.

  • I suspect you will only want one function that takes snapshots and drives drawing into the different canvases. It is likely you can only get media into one source at a time. For example, if I used your code in iframes I could still only populate one video element with the stream.

Hi Jonathan.

Thank you very much for your answer.

I am not really familiar with coding so I just copy-paste this code from an example I found. I don’t want to use the snapshot() function but when I delete it then the camera doesn’t work.

I changed the IDs but still the camera is displayed only in one box.