【问题标题】:Get video element in ts file获取ts文件中的视频元素
【发布时间】:2019-02-11 12:58:21
【问题描述】:

我是 Ionic 的新手,正在开发 Ionic 4。我想从视频 src 中获取帧缩略图。为此,我必须在我的 .ts 文件中获取视频元素。我尝试使用 ViewChild,如link 所示。但是当我在浏览器中运行它时,我收到了这个错误TypeError: Cannot read property 'addEventListener' of undefined。有什么我想念的吗?我也以同样的方式获得了 Canvas 的元素,我认为它可以工作。但它不适用于视频标签。

export class UploadvidPage implements OnInit {
  @ViewChild('myVideo') myVideo: ElementRef;
  @ViewChild('myCanvas') myCanvas: ElementRef;
  public isAndroid: boolean;
  public imageUrl: any;
  public fpath;
  public video: any;
  public canvas: any;
  public context: CanvasRenderingContext2D;
  
  ngAfterViewInit(): void {
    this.video = this.myVideo.nativeElement;
    this.canvas = this.myCanvas.nativeElement;
    this.context =(<HTMLCanvasElement>this.canvas).getContext('2d');
  }
  
  handleFileSelect(evt){
    
    let files = evt.target.files;
    let file = files[0] 
    var binaryData = [];
    binaryData.push(file);
    this.fpath = this.sanitizer.bypassSecurityTrustUrl(URL.createObjectURL(new Blob(binaryData, {type: "application/zip"})));
   
    var w,h,ratio;

    //below code for setting snap of video into canvas
    this.video.addEventListener('loadedmetadata', function() {
      console.log('Got into video.addEventListener()');
      ratio = this.video.videoWidth/this.video.videoHeight;
      w = this.video.videoWidth-100;
      h = w/ratio,10;
      this.video.width = w;
      this.canvas.height = h;
      snap();
    },false);
  
    function snap() {
      console.log('Got into snap()');
      this.context.fillRect(0,0,w,h);
      this.context.drawImage(this.video,0,0,w,h);
    }



  }
  
  
}  
<input  id="file-input" type="file" accept="video/*" (change)="handleFileSelect($event)">
<video *ngIf="fpath" id="myVideo" #myVideo controls>
     <source [src]="fpath" id="source">
</video>
<canvas #myCanvas width="640" height="480"></canvas>

【问题讨论】:

    标签: html ionic-framework


    【解决方案1】:

    您需要重构代码。因为,在您发布的代码中,在查看初始化 (ViewChild+ ngAfterViewInit) 时,您的视频还不存在,因为 *ngIf="fpath"(其中 fpath 仅在用户选择时填充,所以在 handleFileSelect而不是在视图初始化)。

    多种解决方案:

    • 删除 *ngIf(最好隐藏它?)。这样ViewChild+ ngAfterViewInit 就能完美运行

    • *ngIfevaluates 为 true 时动态检索视频模板引用(并在尝试使用之前让 Angular 执行它)。以下代码将在每次解析为 true 时触发 setter:

    @ViewChild('myVideo') set content(content: ElementRef) { this.myVideo = content; }

    +

    延迟您的addEventListener:例如使用setTimeout,以确保角度有时间初始化您的myVideo

    【讨论】:

    • 感谢您的快速回答。现在我收到此错误Cannot read property 'nativeElement' of undefined
    • 编辑了更多细节,有多种解决方案,但我想您了解问题的根源
    • 我尝试了你的第一种方式。它消除了错误,但现在视频没有加载到视频标签中。对于第二种方式,它在this.myVideo 中显示红线。
    • 经过一番检查,我设法使用了第二种方法。现在错误消失了,但图像没有显示在画布中。
    猜你喜欢
    • 2012-12-06
    • 2022-06-11
    • 2021-05-09
    • 2015-04-18
    • 1970-01-01
    • 1970-01-01
    • 2015-03-11
    • 2021-12-21
    • 2011-07-06
    相关资源
    最近更新 更多