Search code examples
javascriptjquerygrailshtml2canvas

Setting value to a hiddenField in html2canvas event


I have a problem with setting value to a hiddentfield in html2canvas onrendered event.

Here is my code snippets:

js:

function saveCanvas()
{
    var data = null;
    html2canvas([document.getElementById('hidTest')],
    {
        onrendered: function(canvas)
        {
            data = canvas.toDataURL('image/png');
            alert(data);
            jQuery("input[name='hid']").val(data);
            alert(jQuery('#hid').val());
        }
    });
    alert(data);
}

html:

...
<g:hiddenField name="hid"/>
...

What I note is that the alert outside the onrendered event will fire as first. Also in alert(data) in onrendered event I see that data is create corectly, but it isn't assign to the hiddenField (hid), and "alert(jQuery('#hid').val())" shows me that my hiddenField is undefined. I will be very grateful for help!


Solution

  • I find solution. I think jQuery is too slow? And pure js works fine:

    instead of this:

    html2canvas([document.getElementById('hidTest')],
    {
        onrendered: function(canvas)
        {
            data = canvas.toDataURL('image/png');
            jQuery("input[name='hid']").val(data);
        }
    });
    

    I use this:

    html2canvas([document.getElementById('hidTest')],
    {
        onrendered: function(canvas)
        {
            var dataBind = document.getElementById('hid');
            data = canvas.toDataURL('image/png');
            dataBind.value = data;
        }
    });
    

    Edit

    It's a bit strange but something like this also works fine:

    html2canvas([document.getElementById('hidTest')],
    {
        onrendered: function(canvas)
        {
            jQuery("input[name='hid']").val(canvas.toDataURL('image/png'));
        }
    });