2017-02-27 91 views
2

我使用網絡攝像頭流創建視頻對象以應用於畫布。我可以在沒有在DOM中繪製它的情況下獲得網絡攝像頭流分辨率嗎?獲取攝像頭流分辨率而不添加視頻到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() 
}) 

回答

0

您可以使用視頻元素的videoWidthvideoHeight屬性來獲取其resolulation (寬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事件被觸發後,必須調用這些屬性。