Typescript-未捕获的DOMException:无法在“ HTMLCanvasElement”上执行“ toDataURL”:可能无法导出污染的画布 [英] Typescript - Uncaught DOMException: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported

查看:650
本文介绍了Typescript-未捕获的DOMException:无法在“ HTMLCanvasElement”上执行“ toDataURL”:可能无法导出污染的画布的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一个Ionic应用程序,尝试将URL中的图像转换为base64时遇到此错误。

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.

我的代码如下:

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

我还阅读了其他设置 anonymous crossOrigin 中是解决方案,但我已经有了。

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

希望您能提供帮助我,谢谢。

Hope you can help me, thanks.

编辑1

作为注释,我不第一次将图像转换为base64时无法得到此结果,但在以下几次尝试编辑图像时得到此结果。

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.

推荐答案

与第一篇文章中的方法不同,我改用了Angular的HttpClient下载图像,然后获取其base64。

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

代码:

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

这篇关于Typescript-未捕获的DOMException:无法在“ HTMLCanvasElement”上执行“ toDataURL”:可能无法导出污染的画布的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆