使用Chart JS生成空白PNG图像,使用toBase64Image()函数

6

我正在尝试保存使用Chart.JS图表库创建的图表副本。当我使用.toBase64Image()函数来显示或保存.png图像时,我得到了一个空白图像。我已经尝试在img标签中显示和用PHP保存图像。save64Img是我的函数来显示/保存图像。有没有人能够成功使用这个功能?

lineOptions = {
        scaleShowGridLines : true,
        scaleGridLineColor : "rgba(0,0,0,.05)",
        scaleGridLineWidth : 1,
        bezierCurve : false,
        pointDot : true,
        pointDotRadius : 4,
        pointDotStrokeWidth : 1,
        pointHitDetectionRadius : 20,
        datasetStroke : true,
        datasetStrokeWidth : 1,
        datasetFill : true,
        responsive: true,      
        scaleOverride : true,
        scaleSteps : 5,
        scaleStepWidth : 20,
        scaleStartValue : 0

    }

    lineChart = {
            labels : label,
            datasets : [
                {
                    label: "stat1",
                    fillColor : "rgba(128,0,0,0.2)",
                    strokeColor : "rgba(128,0,0,1)",
                    pointColor : "rgba(128,0,0,1)",
                    pointStrokeColor : "#fff",
                    pointHighlightFill : "#fff",
                    pointHighlightStroke : "rgba(128,0,0,1)",
                    data : stat1
                },
                {
                    label: "stat2",
                    fillColor : "rgba(151,187,205,0.2)",
                    strokeColor : "rgba(151,187,205,1)",
                    pointColor : "rgba(151,187,205,1)",
                    pointStrokeColor : "#fff",
                    pointHighlightFill : "#fff",
                    pointHighlightStroke : "rgba(151,187,205,1)",
                    data : stat2
                }
            ]

    };

var myChart = new Chart(ctx).Line(lineChart, lineOptions);

save64Img(myChart.toBase64Image());

----------

<?php 
$data = base64_decode(preg_replace('#^data:image/\w+;base64,#i', '', $img));

file_put_contents('/tmp/image.png', $data);

?>
2个回答

1
我知道你的问题已经有一段时间了,但在 Chart.js v2 中,你需要在动画选项中使用 onComplete 方法。
animation: {
    duration: 1500,
    onComplete: function (animation) { 
        this.toBase64Image();
}

1
谢谢!我花了很多时间找到这个对我有用的答案。 - MartinsB
请问您能否分享完整的代码。 - MIK

-1

你需要在额外的回调函数中调用save64Img(myChart.toBase64Image())。你可以将这个回调函数添加到选项中。

lineOptions = {
    onAnimationComplete: function () {
       save64Img(myChart.toBase64Image());
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接