简体   繁体   中英

Get webcam stream resolution without adding video to DOM?

I'm creating a video-object with a webcam stream to apply to a canvas. Can I get the webcam streams resolution without drawing it in the DOM?

// Triangel side length
const video = document.createElement('video')
const v = document.getElementById('video')
const vc = v.getContext('2d')
navigator.mediaDevices.getUserMedia({video: true}).then((stream) => {
  video.src = window.URL.createObjectURL(stream)
  console.log(video)
  video.play()
  //this is where I want the stream resolution.
  vc.drawImage(video, -250, -250)

  loop()
})

You can use videoWidth and videoHeight property of a video element to get its resolulation (width x height) , even without adding the element to the DOM. These properties return an intrinsic width / height of a video in CSS pixels.

const video = document.createElement('video')
const v = document.getElementById('video')
const vc = v.getContext('2d')
navigator.mediaDevices.getUserMedia({
    video: true
}).then((stream) => {
    video.src = window.URL.createObjectURL(stream)
    console.log(video)
    video.play()
    // get video / stream resolution
    video.onloadedmetadata = function() {
        console.log('resolution: ' + this.videoWidth + ' x ' + this.videoHeight);
    };
    vc.drawImage(video, -250, -250)
    loop()
})

note : you must call for these properties after the loadedmetadata event is fired.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM