Monday, 24 April 2017

Chart.js export to PNG file

I'm trying to use chart.js to export a chart to a PNG file from a node.js app.

The documentation says that I should use toBase64Image(), and some answers I found suggest that I should do this within an onComplete function within the animation settings. But I'm not understanding how to save a file.

This is what I've currently got:

<div class="col-sm-6">
<canvas id="visitsChart" width="400" height="200"></canvas>
<script>
var ctx = document.getElementById("visitsChart").getContext("2d");
var visitsChart = new Chart(ctx, {
    type: 'bar',
    data: {
        labels: [<%= labels %>],
        datasets: [{
            label: '<%= legend %>',
            data: [<%= visits %>],
            backgroundColor: [
                'rgba(255, 99, 132, 0.2)',

          ],
            borderColor: [
                'rgba(255,99,132,1)',

            ],
            borderWidth: 1
        }]
    },
    options: {
            responsive: true,
                        scales: {
                                yAxes: [{
                                        ticks: {
                                                beginAtZero:true
                                        }
                                }]
                        },
            animation: {
                duration: 1500,
                onComplete: function (sendChart) {
                    this.toBase64Image();
                }
            }
        }
});

function clearCanvas() {
    c.height = 300;
}
</script>
</div>

I'm confused about what to do next to save the chart to something like /tmp/chart.png.



via Sean

No comments:

Post a Comment