I am trying to "clone" a table to an image in html, the code works but not all the time, it only work at the 2nd or 3rd trigger of the button.
The picture below shows that at the first click the image table is not displayed only a box is displayed. BUT at the second click it is displayed. I think this got something to do with the "image loding concept" but I am not that familiar with that and there are questions related to this one but no answers given or the answer given does not work.
my code is somehow similar to the fiddle below but i have a dynamic table. it can change anytime
$(document).ready(function() {
var image2 = new Image();
$("#more").click(function() {
var tableImage;
html2canvas($("#dataTable"), {
onrendered: function(canvas) {
tableImage = canvas.toDataURL("image/png");
image2.src = tableImage;
},
allowTaint: false
});
$('.reportContents').append('<input id="title" style="border:none;" name="title" type="hidden" value="null"/>');
$('.reportContents').append('<input type="hidden" id="imageSrc" name = "imageSrc" value="' + tableImage + '"/>');
$('.reportContents').append('<img style="width: 90%;" id="image" src="' + image2.src + '">');
});
});
You are trying to append the derived image before it has been completed. Move the append function inside the html2canvas function:
$(document).ready(function() {
var image2 = new Image();
$("#more").click(function() {
var tableImage;
html2canvas($("#dataTable"), {
onrendered: function(canvas) {
tableImage = canvas.toDataURL("image/png");
image2.src = tableImage;
$('.reportContents').append('<input id="title" style="border:none;" name="title" type="hidden" value="null"/>');
$('.reportContents').append('<input type="hidden" id="imageSrc" name = "imageSrc" value="' + tableImage + '"/>');
$('.reportContents').append('<img style="width: 90%;" id="image" src="' + image2.src + '">');
},
allowTaint: false
});
});
});
Updated FIDDLE