Reputation: 907
I want to draw a base64 String into a canvas bur I always get the error
TypeError: Argument 1 of CanvasRenderingContext2D.drawImage could not be converted to any of: HTMLImageElement, HTMLCanvasElement, HTMLVideoElement.
I did google it, but I still don't know what I did wrong.
var canvas = document.createElement('canvas');
document.body.appendChild(canvas);
var ctx = canvas.getContext("2d");
var data = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAIAAAACDbGyAAAAAXNSR0IArs4c6QAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB9oMCRUiMrIBQVkAAAAZdEVYdENvbW1lbnQAQ3JlYXRlZCB3aXRoIEdJTVBXgQ4XAAAADElEQVQI12NgoC4AAABQAAEiE+h1AAAAAElFTkSuQmCC";
ctx.drawImage(data, 0, 0);
Upvotes: 4
Views: 13233
Reputation: 3496
This solution is best
https://stackoverflow.com/a/20285053/296373
Upvotes: -2
Reputation: 115970
drawImage
expects its first argument to be an image, video, or canvas (i.e., HTMLImageElement
, HTMLVideoElement
, or HTMLCanvasElement
), not a string.
You need to construct a new image, and then supply that new image object with your base64 source. Once the image loads, you can add the image to your canvas:
var img = new Image();
img.src = "data:image/png;base64,iVBORw0KGgoAAAANSUh...";
img.onload = function() {
ctx.drawImage(img, 0, 0);
}
Upvotes: 13