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!
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" />
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With