HTML5video尺寸

我正在尝试使用javascript叠加到页面上的video的尺寸,但是它将返回海报图片的尺寸而不是实际的video,因为它似乎是在video加载之前计算的。 任何想法我应该如何处理这个问题来纠正它?

提前谢谢了。

<video id="foo" src="foo.mp4"></video> var vid = document.getElementById("foo"); vid.videoHeight; // returns the intrinsic height of the video vid.videoWidth; // returns the intrinsic width of the video 

规格: https : //html.spec.whatwg.org/multipage/embedded-content.html#the-video-element

应该指出的是,这个解决scheme实际上在现代浏览器中不起作用,因为videoWidth和videoHeight属性在“loadedmetadata”事件触发之后才会被设置。

如果在渲染VIDEO元素后碰巧查询这些属性,它有时可能会工作,但在大多数情况下,这两个属性的值都会返回0。

为了保证你得到正确的属性值,你需要做一些事情:

 var v = document.getElementById("myVideo"); v.addEventListener( "loadedmetadata", function (e) { var width = this.videoWidth, height = this.videoHeight; }, false ); 

注:我没有打扰会计使用attachEvent而不是addEventListener的Internet Explorer 9之前的版本,因为该浏览器的9以前版本不支持HTML5video。

监听用户代理刚刚确定媒体资源的持续时间和维度时,调度的loadedmetadata事件

第4.7.10.16节事件总结

https://www.w3.org/TR/html5/embedded-content-0.html#event-media-loadedmetadata

 videoTagRef.addEventListener('loadedmetadata', function(e){ console.log(videoTagRef.videoWidth, videoTagRef.videoHeight); }); 

准备好使用function

这里有一个准备使用的function,它可以asynchronous地返回video的尺寸, 而不会改变文档中的任何内容

 // ---- Definitions ----- // /** Returns the dimensions of a video asynchrounsly. @param {String} url Url of the video to get dimensions from. @return {Promise} Promise which returns the dimensions of the video in 'width' and 'height' properties. */ function getVideoDimensionsOf(url){ return new Promise(function(resolve){ // create the video element let video = document.createElement('video'); // place a listener on it video.addEventListener( "loadedmetadata", function () { // retrieve dimensions let height = this.videoHeight; let width = this.videoWidth; // send back result resolve({ height : height, width : width }); }, false ); // start download meta-datas video.src = url; }); } // ---- Usation ---- // getVideoDimensionsOf("VfE_html5.mp4") .then(function(dimensions){ console.log("Video width: " + dimensions.width) ; console.log("Video height: " + dimensions.height) ; });