将 Base64 PNG 数据转换为 HTML5画布

我想加载一个用 Base64编码的 PNG 图像到画布元素:

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

在 Chrome8中我得到了错误: Uncaught TypeError: Type error

在 Firefox 的 Firebug 中: “对象的类型与与对象相关的参数的预期类型不兼容”代码: “17”

在 base64中是我在 GIMP 中创建的5x5px 黑色 PNG 正方形,并在 GNU/Linux 的 base64程序中将其转换为 base64。

154289 次浏览

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.

Jerryf's answer is fine, except for one flaw.

The onload event should be set before the src. Sometimes the src can be loaded instantly and never fire the onload event.

(Like Totty.js pointed out.)

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