【问题标题】:How to print canvas element by using javascript print method?如何使用 javascript 打印方法打印画布元素?
【发布时间】:2017-02-05 02:31:34
【问题描述】:

如何打印创建的画布元素,该元素上使用 javascript 绘制了一些内容?我的打印预览显示一个空白框,而不是画布元素中的内容?

首先我使用 html2canvas 创建我的画布图像,然后我看到该图像已创建。但我无法打印包含相关图像的 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('<img src="'+canvasImg+'" alt="">');
}
});

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

【问题讨论】:

  • 评论完后试试 printWindow.close(); chrome 有一些问题。
  • 我试过了,但没有任何改变。

标签: javascript jquery html canvas


【解决方案1】:

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

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

    &lt;a id="btn-print" onclick="print()"&gt;Print&lt;/a&gt;
  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;
      }
    }

这让您只打印画布。
我没有跨浏览器对此进行测试,但它绝对适用于 Chrome。

【讨论】:

  • 这应该是支持跨浏览器的,根据caniuse。此外,如果您想隐藏除少数之外的所有元素,您可以使用 :not() 伪类::not(.canvas_element):not(.element_that_should_remain_visible) {display: none;}
  • 我需要一个 JS 解决方案所以this worked for me
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-09-15
  • 1970-01-01
  • 2016-04-26
  • 1970-01-01
相关资源
最近更新 更多