简体   繁体   English

Canvas.toDataURL()未捕获TypeError:undefined不是函数

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

I'm using a plugin called html2canvas to convert some html on my page into a canvas element. 我正在使用一个名为html2canvas的插件将我页面上的一些html转换为canvas元素。 I then want to save that canvas as an image. 然后我想将该画布保存为图像。 Unfortunately I keep encountering the error in the title. 不幸的是,我一直遇到标题中的错误。 I have tried with different variable names, with different html, etc. But keep encountering the same error. 我尝试过不同的变量名,不同的html等。但是仍然遇到同样的错误。 Here is my code (triggered on a button click): 这是我的代码(按下按钮时触发):

JS 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
    }

Ok, I found my problem was I was trying to call toDataURL() on my jQuery object rather than my canvas element. 好吧,我发现我的问题是我试图在我的jQuery对象而不是我的canvas元素上调用toDataURL() To fix this I used .get(0) . 为了解决这个问题,我使用了.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
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM