Base64 png数据到html5canvas

美好的一天程序员,

我想在base64中加载一个PNG图像到canvas元素。 我有这个代码:

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

在Chrome 8中,我得到了这个:Uncaught TypeError:Type error

在Firefox的Firebug中:对象的types与与对象“代码:”相关联的参数的期望types不兼容

在那个base64是5x5px的黑色PNG广场,我已经在GIMP和GNU / Linux的程序base64把它变成base64。

非常感谢你的答案。

通过它的外观,你需要实际上像这样传递drawImage一个图像对象

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

我已经尝试了铬,它工作正常。

杰里夫的回答很好,除了一个缺陷。

onload事件应该在src之前设置。 有时src可以被立即加载并且不会触发onload事件。

(就像Totty.js指出的那样)

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