使用Chart JS的空白PNG图像.toBase64Image()函数

Blank PNG image using Chart JS . toBase64Image() function

本文关键字:toBase64Image 函数 图像 PNG Chart JS 空白 使用      更新时间:2023-09-26

我试图保存使用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);
?>

我知道自从你问这个问题以来已经有一段时间了,但是在Chart.js v2中,你必须在动画选项中使用onComplete方法。

animation: {
    duration: 1500,
    onComplete: function (animation) { 
        this.toBase64Image();
}

您必须通过一个额外的回调调用save64Img(myChart.toBase64Image())。您可以将此回调添加到选项

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