如何使用blob和filesaver将Chart JS图表保存为没有黑色背景的图像?

use*_*844 8 blob html5-canvas chart.js filesaver.js

$("#NoBidsChart").get(0).toBlob(function(value) {
    saveAs(value, "Summary.jpg");
});
Run Code Online (Sandbox Code Playgroud)

这里我使用Chart JS(v2.5.0)来渲染图表.当我尝试使用Canvas导出图表到Blob转换器和filesaver.js时,我得到黑色背景.那么我如何获得具有自定义背景颜色(最好是白色)的图像?

Ann*_*unn 12

正如我在对已接受答案的评论中所述,让我感到困扰的是 beforeDraw 事件导致 fillRect 代码被多次调用。(据我所知,每个数据点一次。)

但是当我调用任何其他事件时,我无法使用这种方法。但是,我只是采用了以下描述的编码方法:https : //stackoverflow.com/a/50126796/165164 并将其插入注册以在 afterRender 事件上运行的代码中,它执行我想要的操作:运行一次并离开后台白色的。

Chart.plugins.register({
    afterRender: function(c) {
        console.log("afterRender called");
        var ctx = c.chart.ctx;
        ctx.save();
        // This line is apparently essential to getting the
        // fill to go behind the drawn graph, not on top of it.
        // Technique is taken from:
        // /sf/answers/3508875751/
        ctx.globalCompositeOperation = 'destination-over';
        ctx.fillStyle = 'white';
        ctx.fillRect(0, 0, c.chart.width, c.chart.height);
        ctx.restore();
    }
});
Run Code Online (Sandbox Code Playgroud)

请访问(并投票)其他已发布问题的链接答案。


ɢʀᴜ*_*ᴜɴᴛ 11

如果你想要一个自定义的背景颜色,你必须用你喜欢的颜色绘制背景,你可以这样做,像这样...

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);
    }
});
Run Code Online (Sandbox Code Playgroud)

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");
    });
});
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/1.3.3/FileSaver.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js"></script>
<button id="save">Save</button>
<canvas id="NoBidsChart"></canvas>
Run Code Online (Sandbox Code Playgroud)