无法加载Base64的字符串作为画布 [英] Trouble loading Base64 string to canvas

查看:636
本文介绍了无法加载Base64的字符串作为画布的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从我的数据库加载Base64的字符串的画布。

I'm trying to load a Base64 string from my database to a canvas.

我从做相反的方法获得这个字符串:我把它在画布上绘制后保存到我的数据库。所以,现在我想载入它到其他画布。我已经试过这code,我拿起网上和其他地方就在这里,但计算器它似乎不工作。

I obtained this string from doing the reverse method: I saved it to my database after drawing on a canvas. So, now I want to load it back onto another canvas. I have tried this code which I picked up on the web and somewhere else here on StackOverflow but it doesn't seem to work.

<script type="text/javascript">
  $(document).ready(function(){
    var canvas = document.getElementById("loading_canvas");
    var ctx = canvas.getContext("2d");

    var image = new Image();

    $.post('doodles/load', function(data) {
      image.src = data;
    });
    ctx.drawImage(image, 0, 0);
  });
</script>

我在加载数据从我的数据库使用Ajax调用。

I load in the data from my database with an ajax call.

如果我警报()数据变种,它会显示连接codeD Base64编码字符串。所以它并没有真正去错了..我只是结束了一个空白的画布所有的时间。

If I alert() the data var, it displays the encoded Base64 string. So it doesn't really go wrong there.. I just end up with an empty canvas all the time.

任何人都知道我在做什么错在这里?非常感谢!

Anyone know what I'm doing wrong here? Thanks a lot!

推荐答案

尝试图像的加载事件后绘制图像:

Try drawing the image after the image's load event:

var image = new Image();
image.onload = function () {
    ctx.drawImage(image, 0, 0);
}

$.post('doodles/load', function(data) {
    image.src = data;
});

的src 需要有一个完整的数据网址,而并非只是一堆的base64数据,因此仔细检查过。
示例(从维基百科):

The src needs to have a full data URL and not just a bunch of base64 data, so double-check that too. Example (from Wikipedia):

<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==" alt="Red dot" />

这篇关于无法加载Base64的字符串作为画布的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆