我使用名为html2canvas的插件将我页面上的某些html转换为canvas元素。然后我想将该画布保存为图像。不幸的是,我一直遇到标题中的错误。我尝试过不同的变量名,不同的html等。但是仍然遇到同样的错误。这是我的代码(按下按钮时触发):
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
}
答案 0 :(得分:14)
好的,我发现我的问题是我试图在我的jQuery对象上调用toDataURL()
而不是我的canvas元素。为了解决这个问题,我使用了.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
}