Canvas.toDataURL () Uncaught TypeError: undefined is not a function

I am using a plugin called html2canvas to convert some html on my page to a canvas element. Then I want to save this canvas as an image. Unfortunately, I continue to run into a misspelled title. I've tried with different variable names, different html, etc. But keep facing the same error. Here is my code (fires on button click):

Js

function generate(){
        html2canvas($('#b2_1'), {
            onrendered: function(canvas) {
                canvas.setAttribute("id", "canvas");
                document.body.appendChild(canvas);
            }
        });//this all works, the canvas appears as expected

        var myCanvas = $(document).find('#canvas');
        myCanvas.css("margin-left", "50px");//this was to test I was selecting the right element, the canvas moves
        var myImg = myCanvas.toDataURL();//code breaks here
    }

      

+3


source to share


1 answer


Ok, I found that my problem was what I was trying to call toDataURL()

on my jQuery object, not the canvas element. To fix this, I used .get(0)

. Full code below:



function generate(){
        html2canvas($('#b2_1'), {
            onrendered: function(canvas) {
                canvas.setAttribute("id", "canvas");
                document.body.appendChild(canvas);
            }
        });//this all works, the canvas appears as expected

        var myCanvas = $(document).find('#canvas');
        myCanvas.css("margin-left", "50px");
        var myImg = myCanvas.get(0).toDataURL();//have to get the canvas element from the jquery object
    }

      

+9


source







All Articles