HTML5视频尺寸

Ell*_*iot 85 javascript jquery html5-video

我试图让其中的我覆盖到与JavaScript的网页视频的尺寸,但它返回的海报图像的尺寸,而不是实际的视频,因为它似乎被加载视频前它被计算.

nat*_*e75 123

应该注意的是,Sime Vidas上面当前接受的解决方案实际上并不适用于现代浏览器,因为直到"loadedmetadata"事件被触发之后才设置videoWidth和videoHeight属性.

如果您在呈现VIDEO元素后碰巧要查询这些属性,它有时可能会起作用,但在大多数情况下,这将为两个属性返回值0.

为了保证您获得正确的属性值,您需要执行以下操作:

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

注意:我没有考虑使用attachEvent而不是addEventListener的前9版Internet Explorer,因为该浏览器的9前版本不支持HTML5视频.

  • 这不会在 100% 的情况下起作用。在极少数情况下,当 `loadedmetadata` 触发时,videoWidth 和 videoHeight 将为零。我刚刚在 Chromium 69 上看到它。监听 `loadeddata` 是一个更安全的选择。 (4认同)
  • 不幸的是,这不适用于适用于 Android 49 的 Chrome;只有当视频开始播放时,信息才可用。对此有何进一步见解?PS1:我只尝试了使用文件选择器输入元素选择的本地文件的 URL。PS2:它确实适用于 iOS Safari。 (2认同)

Šim*_*das 83

<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
Run Code Online (Sandbox Code Playgroud)

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

  • 使用“URL.createObjectURL( file )”播放本地文件时始终为零 (2认同)

Yai*_*pro 14

准备使用功能

这是一个随时可用的功能,可以异常地返回视频的尺寸,而无需更改文档中的任何内容.

// ---- 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;
	});
}


// ---- Use ---- //
getVideoDimensionsOf("http://clips.vorwaerts-gmbh.de/VfE_html5.mp4")
   .then(({width, height}) => {
	console.log("Video width: " + width) ;
	console.log("Video height: " + height) ;
    });
Run Code Online (Sandbox Code Playgroud)

如果你想看的话,这是用于片段的视频:Big Buck Bunny


Jua*_*des 12

侦听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);
});
Run Code Online (Sandbox Code Playgroud)