问题
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