html2canvas - 错误 - 对象 HTMLCanvasElement

html2canvas - error - object HTMLCanvasElement

我需要使用 javascript 打印 div.. 这个 div 的内容是生成的条形码.. 使用打印 div 元素的正常方法不起作用,因为条形码图像是由 php 文件生成的并且不会出现在打印页面中..所以我决定使用 html2canvas 方法来'render' div 然后打印出来.. 这是我的代码:

HTML:

<div id="source" onClick="capture()"> Some content and img of barcode </div>

JavaScript:

function capture() {
    html2canvas( [ document.getElementById('source') ], {
    onrendered: function (canvas) {
        var mywindow = window.open('', 'my div', 'height=400,width=1000');
        mywindow.document.write('<html><head><title>Print Div:</title>');
        mywindow.document.write('</head><body >');
        mywindow.document.write(canvas);
        mywindow.document.write('</body></html>');
        mywindow.document.close(); // necessary for IE >= 10
        mywindow.focus(); // necessary for IE >= 10

        mywindow.print();
        mywindow.close();

        return true;
}

    });
}

mywindow 打开,但不包含 div 我需要打印的内容.. 我收到此错误:[object HTMLCanvasElement]

感谢关注..

来自 html2canvas 文档:

onrendered: function(canvas) {
   // canvas is the final rendered <canvas> element
}

canvas 是一个 DOM 元素。你不能document.write DOM元素(这是一个字符串方法),输出[HTMLCanvasElement]是JS如何将DOM元素转换为字符串(这不是错误)。如果弹出窗口与父级 window 在同一个域中,您应该可以做到 mywindow.document.appendChild(canvas)Else if it's not 一个可能的解决方法是,- 在您的 onrendered 回调中-,执行:

var canvasData = canvas.toDataURL();
mywindow.document.write('<img src="' + canvasData + '">');