Base64 PNG数据到HTML5画布

我想将以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中,这是:“对象的类型与与该对象关联的参数的预期类型不兼容”代码:“ 17”

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

回答:

从外观上看,您实际上需要像这样传递一个imageImage对象

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>

我已经在chrome中尝试过了,效果很好。

以上是 Base64 PNG数据到HTML5画布 的全部内容, 来源链接: utcz.com/qa/400420.html

回到顶部