Base64 PNG data to HTML5 canvas

Tomáš Nesrovnal picture Tomáš Nesrovnal · Dec 10, 2010 · Viewed 119.8k times · Source

I want to load a PNG image encoded in Base64 to canvas element. I have this code:

<html>
<head>
</head>
<body>
<canvas id="c"></canvas>
<script type="text/javascript">

var canvas = document.getElementById("c");
var ctx = canvas.getContext("2d");

data =  "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAIAAAACDbGyAAAAAXNSR0IArs4c6QAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB9oMCRUiMrIBQVkAAAAZdEVYdENvbW1lbnQAQ3JlYXRlZCB3aXRoIEdJTVBXgQ4XAAAADElEQVQI12NgoC4AAABQAAEiE+h1AAAAAElFTkSuQmCC";

ctx.drawImage(data, 0, 0);

</script>
</body>
</html>

In Chrome 8 I get the error: Uncaught TypeError: Type error

And in Firefox's Firebug this: "The type of an object is incompatible with the expected type of the parameter associated to the object" code: "17"

In that base64 is 5x5px black PNG square that I have made in GIMP and turn it to base64 in GNU/Linux's program base64.

Answer

Jerryf picture Jerryf · Dec 10, 2010

By the looks of it you need to actually pass drawImage an image object like so

var canvas = document.getElementById("c");
var ctx = canvas.getContext("2d");

var image = new Image();
image.onload = function() {
  ctx.drawImage(image, 0, 0);
};
image.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAIAAAACDbGyAAAAAXNSR0IArs4c6QAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB9oMCRUiMrIBQVkAAAAZdEVYdENvbW1lbnQAQ3JlYXRlZCB3aXRoIEdJTVBXgQ4XAAAADElEQVQI12NgoC4AAABQAAEiE+h1AAAAAElFTkSuQmCC";
<canvas id="c"></canvas>

I've tried it in chrome and it works fine.