Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Base64 PNG data to HTML5 canvas

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.

like image 595
Tomáš Nesrovnal Avatar asked Dec 10 '10 13:12

Tomáš Nesrovnal


People also ask

How do I show base64 in HTML?

Images encoded with Base64 can be embedded in HTML by using the <img> tag. This can help to increase the page load time for smaller images by saving the browser from making additional HTTP requests.

Can a PNG be base64?

The PNG images are binary files but the base64 strings are textual data. It's often convenient to encode PNG to base64 as it allows you to save images in text files. This utility also allows you to specify the length of base64 lines.

What is base64 data image PNG?

data:image/png;base64 tells the browser that the data is inline, is a png image and is in this case base64 encoded. The encoding is needed because png images can contain bytes that are invalid inside a HTML document (or within the HTTP protocol even).


1 Answers

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.

like image 166
Jerryf Avatar answered Oct 13 '22 23:10

Jerryf