快速打印HTML5画布

Der*_*rin 8 javascript jquery html5 canvas

我想将画布图像直接发送/打印到默认打印机.这意味着快速打印.

任何人都可以提示.

Javascript或jQuery.

Raz*_*aza 26

我搜索了很多,找到了一个完美的解决方案:)使用onclick事件

function printCanvas()  
{  
    var dataUrl = document.getElementById('anycanvas').toDataURL(); //attempt to save base64 string to server using this var  
    var windowContent = '<!DOCTYPE html>';
    windowContent += '<html>'
    windowContent += '<head><title>Print canvas</title></head>';
    windowContent += '<body>'
    windowContent += '<img src="' + dataUrl + '">';
    windowContent += '</body>';
    windowContent += '</html>';
    var printWin = window.open('','','width=340,height=260');
    printWin.document.open();
    printWin.document.write(windowContent);
    printWin.document.close();
    printWin.focus();
    printWin.print();
    printWin.close();
}
Run Code Online (Sandbox Code Playgroud)

  • @PreyashDesai如果我没记错的话,当使用javascript打印时,打印对话框将始终在打印前显示以提示用户. (3认同)
  • 这是我需要的,但要当心!我的页面加载速度非常慢。可以在页面加载之前调用`printWin.print()`。最好在创建的页面的“ head”中添加一些javascript:`window.onload = function(){window.print(); 在此示例中,将window.close();}`删除最后两个语句。 (2认同)
  • 这个解决方案不起作用。快速打开一个弹出窗口,仅此而已。 (2认同)

小智 16

我发现第一次打印时,画布是空白的.我添加了一个事件监听器,等待加载图像/文档.现在画布已准备好每次打印.这是为我工作的代码:

const dataUrl = document.getElementById('the-pdf-canvas').toDataURL(); 

let windowContent = '<!DOCTYPE html>';
windowContent += '<html>';
windowContent += '<head><title>Print canvas</title></head>';
windowContent += '<body>';
windowContent += '<img src="' + dataUrl + '">';
windowContent += '</body>';
windowContent += '</html>';

const printWin = window.open('', '', 'width=' + screen.availWidth + ',height=' + screen.availHeight);
printWin.document.open();
printWin.document.write(windowContent); 

printWin.document.addEventListener('load', function() {
    printWin.focus();
    printWin.print();
    printWin.document.close();
    printWin.close();            
}, true);
Run Code Online (Sandbox Code Playgroud)


Paw*_*kal 7

使用printJS和这一行:

printJS({printable: document.querySelector("#your-canvas").toDataURL(), type: 'image', imageStyle: 'width:100%'});
Run Code Online (Sandbox Code Playgroud)

  • 杰出的。我只花了 3 行。第一个用于脚本导入,第二个用于使用 CDN 导入样式,然后第三个衬里在答案中。做得好。我到处尝试了很多答案,但没有任何运气,花了大约 4 个小时就这个主题做了一些更多的定制任务,但最终得到了正确的答案。非常感谢! (2认同)