-1

I would like to crop part of a video that is being played after click of the user. But I am guetting the following error:

ERROR DOMException: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported.

Similar question has already been asked here and there, but they do not solve my issue.

template

<div>
  <video src="url" #myvideo> </video>
  <div class="my-div" (click)="clickBox()" #divPos></div>
<div>

component

clickVideo() {
  this.clickEvent = Observable.fromEvent(this.divPos.nativeElement, 'click')
  .map(event =>  event);
  this.clickEvent.subscribe(event => {
    const canvas: HTMLCanvasElement = this.renderer.createElement('canvas');
    const img = this.renderer.createElement('img');
    let context = canvas.getContext('2d');
    context.drawImage(this.myvideo.nativeElement, event.pageX-10, event.pageY-10, 30, 30);
    let data = canvas.toDataURL('image/png');
    img.setAttribute('src', data);
    this.renderer.appendChild(document.body, img);
  })
}
edkeveked
  • 17,989
  • 10
  • 55
  • 93
  • Sorry, answered the wrong question earlier. Are you testing this from a local drive? Using the file:// protocol? – Steve Padmore Mar 20 '18 at 20:20
  • Why do you mean by testing from a local drive? Because my video is fetched from the server and I want to take picture from that video. So I am not using anything from the drive – edkeveked Mar 20 '18 at 21:41
  • Because that's one of the reasons for getting the 'Tainted' error. You mentioned that the error was on the 'context.drawImage' line, but the error 'Failed to execute 'toDataURL' on 'HTMLCanvasElement' would mean it was on the 'let data = canvas.toDataURL('image/png');' line. Which one is it exactly? – Steve Padmore Mar 20 '18 at 21:47
  • As the error message stated, the error is thrown because of `toDataURL` @StevePadmore; so that is the line causing the error – edkeveked Mar 21 '18 at 15:52

1 Answers1

0

I have finally found the way around. I need to do these two things:

  • The streaming server should enable CORS : Access-Control-Allow-Origin

  • To address the tainted canvas server side, I change the video tag to the following <video src="url" crossorigin="anonymous" #myvideo> </video>

    Trying to set the video tag in the component function clickVideo() might not work as I learnt the hard way, because the client needs to track that information before loading the video.

Community
  • 1
  • 1
edkeveked
  • 17,989
  • 10
  • 55
  • 93