[英]How to get height and width of the video in Angular 2, TypeScript
I need to check if the video is portrait or landscape, for that I am trying to get the height, width of the video this way, 我需要检查视频是纵向还是横向,为此,我尝试通过这种方式获取视频的高度,宽度,
import { Component, OnInit, AfterViewInit } from '@angular/core';
@Component({
selector: 'app-videplayer',
template: `<video id="singleVideo">
<source src="/assets/videoname.mp4" type="video/mp4">
</video>`
})
export class VideplayerComponent implements OnInit, AfterViewInit {
constructor() {}
ngOnInit() {
}
ngAfterViewInit() {
const videoElem: HTMLVideoElement = <HTMLVideoElement>document.getElementById('singleVideo');
const vidH = videoElem.videoHeight;
const vidW = videoElem.videoWidth;
console.log(vidH, vidW); // this returns: 0, 0
}
}
I tried getting the height, width of the video within constructor, ngOnInit and ngAfterViewInit functions but I'm a getting 0 height and with all the time. 我尝试在构造函数,ngOnInit和ngAfterViewInit函数中获取视频的高度,宽度,但一直都得到0高度。
Try with offsetHeight
and offsetWidth
as below: 尝试使用
offsetHeight
和offsetWidth
,如下所示:
const vidH = videoElem.offsetHeight;
const vidW = videoElem.offsetWidth;
And, if it still does not work then try with some timeout
in ngAfterViewInit()
as below: 并且,如果仍然无法正常运行,请尝试在
ngAfterViewInit()
中ngAfterViewInit()
一些timeout
,如下所示:
ngAfterViewInit() {
setTimeout(function () {
const videoElem: HTMLVideoElement = <HTMLVideoElement>document.getElementById('singleVideo');
const vidH = videoElem.offsetHeight;
const vidW = videoElem.offsetWidth;
console.log(vidH, vidW); // this returns: 0, 0
}, 500);
}
From MDN, on the videoHeight/-Width properties: 在MDN的videoHeight / -Width属性上:
If the element's ready state is HAVE_NOTHING, the value is 0
如果元素的就绪状态为HAVE_NOTHING,则值为0
https://developer.mozilla.org/en-US/docs/Web/API/HTMLVideoElement https://developer.mozilla.org/zh-CN/docs/Web/API/HTMLVideoElement
I think your best option here is to set up a readystatechange
event handler, and then inside that check if the state is > 0 (HAVE_NOTHING), and then read the dimensions. 我认为您最好的选择是设置一个
readystatechange
事件处理程序,然后在其中检查状态是否大于0(HAVE_NOTHING),然后读取尺寸。 (Next readyState would be 1/HAVE_METADATA, and from there on the video dimensions should be available.) (下一个readyState将为1 / HAVE_METADATA,并且从此处开始可以使用视频尺寸。)
https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/readyState https://developer.mozilla.org/zh-CN/docs/Web/API/HTMLMediaElement/readyState
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.