Trouble loading Base64 string to canvas

↘锁芯ラ 提交于 2020-01-13 09:46:49

问题


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

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>

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

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!


回答1:


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;
});

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




回答2:


if your data is a base64 data-uri you should move only one line up and everything is working well.

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


来源:https://stackoverflow.com/questions/6386748/trouble-loading-base64-string-to-canvas

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!