【问题标题】:How to fix element.videoHeight in js with WebRTC?如何使用 WebRTC 修复 js 中的 element.videoHeight?
【发布时间】:2019-07-02 23:06:04
【问题描述】:

我需要一些关于我的代码的认真帮助,这让我发疯了! 我正在尝试设置我的视频格式以匹配方形渲染,但我的 js 不会将 element.videoHeight 设置为我定义的值!

我觉得我什么都试过了:在多个地方更改 video.height 和 video.videoHeight,尝试 'loadedmetadata' 方法,清除所有 cookie 和缓存等...

这是我当前的代码:

(function ()
{
    let width = 0;
    let height = 0;
    let streaming = false;
    let video = null;
    let canvas = null;

    function startup()
    {
        video = document.getElementById('webcam');
        canvas = document.getElementById('transit');

        width = video.offsetWidth;
        video.width = width;
        video.height = width;
        document.getElementById('transit').width = width;
        document.getElementById('result').width = width;

        navigator.mediaDevices.getUserMedia({ video: { width: width, height: width }, audio: false })
            .then(function(stream) {
                video.srcObject = stream;
                video.play();
            })
            .catch(function(err) {
                console.log("An error occured: " + err);
            });

        video.addEventListener('canplay', function(ev){
            if (!streaming) {
                height = width;

                video.setAttribute('width', width);
                video.setAttribute('height', width);
                canvas.setAttribute('width', width);
                canvas.setAttribute('height', height);
                streaming = true;
            }
        }, false);
window.addEventListener('load', startup, false);
})();

我希望 video.videoWidth 等于 video.videoHeight。 但是,如果我设法更改代码中的 video.videoWidth(根据某些 console.log),则 video.videoHeight 保持不变!

结果就像我在标签周围放了一个 div 并且 div 是一个正方形,但视频本身仍然是某种 4/3 格式! 奇怪的是,它在我的个人计算机上运行良好,但在其他计算机上却不行,它们都是 Mac OSX ......而且显然使用相同的 js 版本。

帮助! :'(

【问题讨论】:

    标签: javascript video video-streaming height width


    【解决方案1】:

    videoHeight 是一个只读属性,请参阅mdn

    要获得方形渲染(即使视频是 4:3),请使用 CSS 'cover' object-fit 结合宽度和高度。

    【讨论】:

      【解决方案2】:

      其实,谢谢你的回答,但我发现了错误:这是因为视频的清晰度不能超过720px的高度! 所以我只是添加了一个条件,说明:

      if (video.offsetHeight > 720)
          width = 720;
      else
          width = video.offsetWidth;
      

      所以现在我可以进行方形视频渲染了 :)

      【讨论】:

        猜你喜欢
        • 2017-08-07
        • 2022-10-18
        • 2020-05-30
        • 2022-07-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多