Typescript - Uncaught DOMException: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported

落花浮王杯 提交于 2020-01-06 06:13:27

问题


I am building an Ionic App and I am getting this error when I try to convert to base64 an image from an URL.

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

My code is the following:

public getBase64Image(imgUrl: string): Promise<string> {
    if (!imgUrl.includes("http")) {
      return;
    }

    return new Promise<string>(resolve => {
      let img = new Image();

      img.src = imgUrl;
      img.crossOrigin = "anonymous"
      img.onload = (() => {
        let canvas = document.createElement("canvas");
        canvas.width = img.width;
        canvas.height = img.height;
        let ctx = canvas.getContext("2d");
        ctx.drawImage(img, 0, 0);
        let dataURL = canvas.toDataURL("image/png");
        resolve(dataURL);
      });
    });
  }

I've read other questions where setting anonymous in crossOrigin was the solution, but I already have it.

Hope you can help me, thanks.

EDIT 1

As a note, I don't get this the first time that I convert an image to base64 but I get it in the following times I try to edit an image.


回答1:


Instead of the approach in the first post, I've switched to downloading the image using Angular's HttpClient and then getting its base64.

Code:

public getBase64Image(imgUrl: string): Observable<string> {
    return new Observable(observer => {
      this.http.get(imgUrl, { responseType: 'blob' }).subscribe(data => {
        var reader = new FileReader();
        reader.readAsDataURL(data);
        reader.onloadend = () => {
          observer.next(reader.result.toString().replace(":application/octet-stream;", ":image/png;"));
          observer.complete();
        }
      });
    });
  }


来源:https://stackoverflow.com/questions/54108669/typescript-uncaught-domexception-failed-to-execute-todataurl-on-htmlcanvas

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!