Binding WebCam to video element

How do I bind the output of a webcam to the srcObject attribute of a video element?

I have the following video element in my HTML

<video id="video" srcObject.bind="cameraStream" if.bind="cameraStream">Video stream not available.</video>

In my JavaScript file, I have the following

activate() {
    navigator.mediaDevices.getUserMedia({video: true, audio: false})
        .then((stream) => {
            this.cameraStream = stream
            console.log('this.cameraStream', this.cameraStream)
        })
        .catch((err) => {
            console.error(`An error occurred:`, err)
        }) 
}

The page asks for access to the webcam, and I’ve logged the value of this.cameraStream and I get the stream object in the console, but I’m not getting any content in the video object.

Thank you in advance for your help.

Ok, I figured it out.

Problem #1: I should have been using the attached handler instead of the activate handler because the page object may not be loaded in the activate handler.

Problem #2: I needed to use the ref attribute on the video element to reference the element in JS.

Problem #3: I needed to remove the if.bind because the ref="video" attribute will not define this.video if the element is not present because of if.bind evaluating to false.

Here’s the final working code.

HTML

<video id="video" ref="video">Video stream not available.</video>

JS

    attached() {
        let video = this.video

        navigator.mediaDevices
            .getUserMedia({ video: true, audio: false })
            .then((stream) => {
                video.srcObject = stream
                video.play()
            })
            .catch((err) => {
                console.error(`An error occurred:`, err)
            })
    }

4 Likes