获取网络摄像头流分辨率而不向DOM添加视频?

时间:2017-02-27 11:10:01

标签: javascript html5

我正在创建一个带有网络摄像头流的视频对象,以应用于画布。我是否可以在不将其绘制到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()
})

1 个答案:

答案 0 :(得分:0)

您可以使用视频元素的videoWidthvideoHeight属性来获得其解析(宽x高),即使不将该元素添加到DOM也是如此。这些属性以CSS像素为单位返回视频的固有宽度/高度。

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()
})

注意: 您必须在loadedmetadata事件被触发后调用这些属性。