4

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.

Frits
  • 7,341
  • 10
  • 42
  • 60
Niko Lang
  • 847
  • 2
  • 9
  • 17

2 Answers2

13

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);
}
apsillers
  • 112,806
  • 17
  • 235
  • 239
-2

This solution is best

  1. Approach: FileReader fetch

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

Fatih Hayrioğlu
  • 3,458
  • 1
  • 26
  • 46