我有以下代码
function PrintImage(id) {
var canvas = document.getElementById(id);
var win = window.open();
win.document.write("<br><img src='" + canvas.toDataURL() + "'/>");
win.print();
win.location.reload();
}
我正在尝试打印通过Chart JS呈现的图表。它可以在IE中使用,但不能在chrome中使用。有人可以看一下代码,然后告诉我我可能做错了什么。在Chrome中,打印窗口会打开,但全是白色。
谢谢
答案 0 :(得分:0)
runs on JSFiddle下面的代码段。如果您不希望弹出窗口不受chrome have a look at this question.
的影响,请记住为chrome启用弹出窗口
function PrintImage() {
id = 'chart';
var canvas = document.getElementById(id);
var win = window.open(canvas.toDataURL(), '_blank');
win.document.write("<br><img src='" + canvas.toDataURL() + "'/>");
win.print();
win.location.reload();
}
function drawImage(){
var ctx = $("canvas")[0].getContext("2d"),
img = new Image();
img.onload = function(){
ctx.drawImage(img, 0, 0, 500, 500);
$("span").text("Loaded.");
};
img.src = "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQ7udaoWuG0i57WCc7OyxkWG0jCkqMIBa7D7ff2Dk1Fk7rCsoQr";
img.crossOrigin ="anonymous";
$("span").text("Loading...");
}
$("#add").click(drawImage);
$("#print").click(PrintImage);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<title>Canvas Replace</title>
</head>
<body>
<button id="add">Add Image</button><span></span>
<button id= "print">Print Image</button>
<canvas width="500" height="500" id='chart'></canvas>
</body>
</html>