javascript Canvas.toDataURL() 未捕获的类型错误:未定义不是函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26284123/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Canvas.toDataURL() Uncaught TypeError: undefined is not a function
提问by gaynorvader
I'm using a plugin called html2canvas to convert some html on my page into a canvas element. 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. Here is my code (triggered on a button click):
我正在使用一个名为 html2canvas 的插件将我页面上的一些 html 转换为 canvas 元素。然后我想将该画布另存为图像。不幸的是,我一直遇到标题中的错误。我曾尝试使用不同的变量名称、不同的 html 等。但一直遇到相同的错误。这是我的代码(通过单击按钮触发):
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
}
回答by gaynorvader
Ok, I found my problem was I was trying to call toDataURL()
on my jQuery object rather than my canvas element. To fix this I used .get(0)
. Full code below:
好的,我发现我的问题是我试图调用toDataURL()
我的 jQuery 对象而不是我的画布元素。为了解决这个问题,我使用了.get(0)
. 完整代码如下:
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
}