如何使用javascript打印方法打印canvas元素?

如何使用javascript打印创建的canvas元素,其中包含一些内容? 我的打印预览显示一个空白框而不是canvas元素中的内容?

首先,我使用html2canvas创建我的canvas图像,然后我看到该图像已创建。 但我无法打印包含相关图像的div。

IE中我可以在触发按钮两次时看到它。 在第一次单击时,它会打开空白打印预览,在第二次单击时,它会打开相关内容。 但是在chrome中它会立即打开空白内容,它无法加载第二个触发器; 页面冻结。

这是我的代码;

function printDiv(index) { var canvasImg = ""; var divToPrint = document.getElementById('hr'+index); html2canvas(divToPrint, { onrendered: function(canvas) { var canvasImg = canvas.toDataURL("image/jpg"); $('#seckinCanvas').html(''); } }); var printContent = document.getElementById("seckinCanvas"); var windowUrl = ''; var uniqueName = new Date(); var windowName = 'Print' + uniqueName.getTime(); var printWindow = window.open(windowUrl, windowName,'left=500,top=500,width=0,height=0'); printWindow.document.write(printContent.innerHTML); printWindow.document.close(); printWindow.focus(); printWindow.print(); printWindow.close(); } 

这对我有用(不需要JS):

  1. 在HTML中包含一个打印按钮:

     Print 

  2. 将其添加到您的CSS:

     @media print { // Make all your non-canvas things (divs and stuff) disappear: .notCanvas, .alsoNotCanvas, ... { display: none; } // Center your canvas (optional): canvas { padding: 0; margin: auto; display: block; position: absolute; width: 800px; height: 800px; top: 0; bottom: 0; left: 0; right: 0; } } 

这使您可以只打印canvas。
我没有对浏览器进行跨浏览测试,但它肯定适用于Chrome。