Niko Lang
Niko Lang

Reputation: 907

Error when drawing Canvas Picture from base 64 String

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

Here's a fiddle.

Upvotes: 4

Views: 13233

Answers (2)

Fatih Hayrioğlu
Fatih Hayrioğlu

Reputation: 3496

This solution is best

  1. Approach: FileReader fetch

https://stackoverflow.com/a/20285053/296373

Upvotes: -2

apsillers
apsillers

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

Related Questions