一尘不染

Base64 PNG数据到HTML5画布

html

我想将以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。


阅读 378

收藏
2020-05-10

共1个答案

一尘不染

从外观上看,您实际上需要像这样传递一个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中尝试过了,效果很好。

2020-05-10