简体   繁体   中英

How to print canvas element by using javascript print method?

How can I print a created canvas element that has some content drawn on it using javascript? My print preview shows a blank box instead of the contents in the canvas element?

First i create my canvas image by using html2canvas, then i see that image is created. But i couldn't print the div which includes related image.

In IE i can see it when triggered button twice. In first click it opens blank print preview, in second click it opens it with related content. However in chrome it opens blank content at once, it cannot load second trigger; page freezes.

Here is my code;

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

Here's what worked for me (no JS needed):

  1. Include a print button in the HTML:

     <a id="btn-print" onclick="print()">Print</a> 

  2. Add this to your 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; } } 

This lets you print just the canvas.
I didn't cross-browser test this, but it definitely works in Chrome.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM