使用js打印canvas.js图表

时间:2014-10-20 14:56:07

标签: javascript jquery canvas

我想使用javascript打印canvas.js图表​​。 打印代码。

当我点击打印按钮时,浏览器中的打印弹出窗口将显示打印预览。

我该如何解决这个问题?

var html = "<html>";
html += document.getElementById("chartContainerInPT").innerHTML;
html += "</html>";
var printWin = window.open('','','left=0,top=0,width=1,height=1,toolbar=0,scrollbars=0,status  =0');
printWin.document.write(html);
printWin.document.close();
printWin.focus();
printWin.print();
printWin.close();

html代码

<div id="chart_divInPT" class="chart">
    <div id="chartContainerInPT" style="height: 300px; width: 100%;"></div>
</div>
<button class="btn save" type="button" style="float: right;" id="printInPT">Print</button> 

JS

var chart = new CanvasJS.Chart(
    "chartContainerInPT",
    {
        theme : "theme1",
        title : {
        text : ""
    },
    data : [ {
        type : "column",
        dataPoints : [
        {
            label : "Attempted",
            y : chapterWiseResult['noOfAttempt']
        },
        {
            label : "Correct",
            y : chapterWiseResult['noOfCorrect']
        },
        {
            label : "Wrong",
            y : wrong
        },
        {
            label : "Unattempted",
            y : unattempted
        },
        ]
    } ]
});

如何在浏览器中打印图表?

2 个答案:

答案 0 :(得分:0)

作为解决方案,您可以将画布保存为图像

var image = canvas.toDataURL("image/png").replace("image/png", "image/octet-stream");
window.location.href=image;

答案 1 :(得分:0)

2021 年更新

Canvas.js 图表现在添加了打印(pdf、png、jpg)格式功能。 启用导出选项如下

            title: {
                text: "Alarm Statistics",
              },
            **exportEnabled: true**,// enable print option for the chart 

            data: [{...},{...}]

<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript">
window.onload = function () {
    var chart = new CanvasJS.Chart("chartContainer",
    {
        title: {
            text: "Chart with export feature enabled",
        },
        exportEnabled: true,
        axisX:{
            minimum: -900, 
            interval: 100,
        },
        data: [
        {
            type: "area",
            fillOpacity: .4,
            lineThickness: 3,
            dataPoints: [
                { x: -100, y: 71 },
                { x: -200, y: 55 },
                { x: -300, y: 50 },
                { x: -400, y: 65 },
                { x: -500, y: 105, markerType: "circle", markerSize: 9, markerColor: "brown", indexLabel: "Highest" },
                { x: -600, y: 68 },
                { x: -700, y: 28 },
                { x: -800, y: 34 },
                { x: -900, y: 14}
            ]
        }
        ]
    });
    chart.render();
}
</script>
<script type="text/javascript" src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
</head>
<body>
<div id="chartContainer" style="height: 300px; width: 100%;">
</div>
</body>
</html>