How to save Chart JS charts as image without black background using blobs and filesaver?

前端 未结 2 1674
轮回少年
轮回少年 2020-12-05 12:18
$(\"#NoBidsChart\").get(0).toBlob(function(value) {
    saveAs(value, \"Summary.jpg\");
});

Here i am using Chart JS(v2.5.0) for rendering charts.

2条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-05 12:29

    If you want a customized background color then, you'd have to draw a background with your preferred color, and you can do so, like this ...

    var backgroundColor = 'white';
    Chart.plugins.register({
        beforeDraw: function(c) {
            var ctx = c.chart.ctx;
            ctx.fillStyle = backgroundColor;
            ctx.fillRect(0, 0, c.chart.width, c.chart.height);
        }
    });
    

    DEMO

    // draw background
    var backgroundColor = 'white';
    Chart.plugins.register({
        beforeDraw: function(c) {
            var ctx = c.chart.ctx;
            ctx.fillStyle = backgroundColor;
            ctx.fillRect(0, 0, c.chart.width, c.chart.height);
        }
    });
    
    // chart
    var canvas = $('#NoBidsChart').get(0);
    var myChart = new Chart(canvas, {
        type: 'line',
        data: {
            labels: [1, 2, 3, 4, 5],
            datasets: [{
                label: 'Line Chart',
                data: [1, 2, 3, 4, 5],
                backgroundColor: 'rgba(255, 0, 0, 0.2)',
                borderColor: 'rgba(255, 0, 0, 0.5)',
                pointBackgroundColor: 'black'
            }]
        }
    });
    
    // save as image
    $('#save').click(function() {
        canvas.toBlob(function(blob) {
            saveAs(blob, "pretty image.png");
        });
    });
    
    
    
    
    

提交回复
热议问题