gpt4 book ai didi

javascript - html2canvas - 错误 - 对象 HTMLCanvasElement

转载 作者:可可西里 更新时间:2023-11-01 01:00:10 26 4
gpt4 key购买 nike

我需要使用 javascript 打印 div..这个div的内容是生成的条形码..使用打印 div 元素的正常方法不起作用,因为条形码图像是由 php 文件生成的,不会出现在打印页面中。所以我决定使用 html2canvas 方法来“渲染”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 元素转换为字符串(这不是错误) .如果弹出窗口与父窗口位于同一域中,您应该能够执行 mywindow.document.appendChild(canvas)Else if it's not一个可能的解决方法是,- 在您的 onrendered 回调中-,执行:

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

关于javascript - html2canvas - 错误 - 对象 HTMLCanvasElement,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29753041/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com