html2canvas - 错误 - 对象 HTMLCanvasElement

5 html javascript php html2canvas

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

HTML:

<div id="source" onClick="capture()"> Some content and img of barcode </div>
Run Code Online (Sandbox Code Playgroud)

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

    });
}
Run Code Online (Sandbox Code Playgroud)

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

谢谢关注。。

Tyb*_*itz 7

来自html2canvas文档:

onrendered: function(canvas) {
   // canvas is the final rendered <canvas> element
}
Run Code Online (Sandbox Code Playgroud)

canvas是一个 DOM 元素。你不能使用document.writeDOM 元素(它是字符串方法),输出[HTMLCanvasElement]是 JS 如何将 DOM 元素转换为字符串(这不是错误)。如果弹出窗口与父窗口位于同一域中,您应该能够执行mywindow.document.appendChild(canvas). 否则,如果这不是一个可能的解决方法,那么 - 在你的onrendered回调中 - 执行以下操作:

var canvasData = canvas.toDataURL();
mywindow.document.write('<img src="' + canvasData + '">');
Run Code Online (Sandbox Code Playgroud)