Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trouble loading Base64 string to canvas

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!

like image 345
Joris Ooms Avatar asked Jun 17 '11 13:06

Joris Ooms


1 Answers

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

like image 101
Matt Ball Avatar answered Sep 22 '22 10:09

Matt Ball