javascriptlaravelchart.jsbrowsershot

Browsershot not taking snapshot of chartjs


I'm trying to take screenshot of chartjs library which has an interval set via browsershot and it wouldn't execute javascript code. This is my code. All I'm getting is a blank image.

var canvas                               =  $("#statisticsChart");
var values                               =  canvas.data("data");
var snapshotDone                         =  false;

function snapshot() {
    
    snapshotDone                         =  true;
    
    if (canvas.data("snapshot")) {
        
        var url                          =  chart.toBase64Image();
        $("#statisticsChartImage").attr("src", url);
        console.log("snapshot");
    }
    
    return true;
    
}

var config                               =  {
    type                                 :  "line",
    data                                 :  {
        labels                           :  values.labels,
        datasets                         :  [
            {
                label                    :  values.name,
                backgroundColor          :  "rgba(255,99,132,0.2)",
                borderColor              :  "rgba(255,99,132,1)",
                borderWidth              :  2,
                hoverBackgroundColor     :  "rgba(255,99,132,0.4)",
                hoverBorderColor         :  "rgba(255,99,132,1)",
                data                     :  values.values,
            }
        ]
    },
    option                               :  {
        animation                        :  false,
        bezierCurve                      :  false,
        //onAnimationComplete : snapshot,
    }
};

var chart = new Chart(canvas, config);

if (!snapshotDone) {
    setTimeout(snapshot, 1000);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<canvas
    id="statisticsChart"
    data-data="{{ json_encode($patient->getChartData()) }}"
    data-snapshot="{{ $snapshot ?? false }}"
></canvas>
<img id="statisticsChartImage" />

$shot = Browsershot::html(view("partials.charts.patient-treatments-weightloss-chart", ["patient" => $patient, "snapshot" => true])->render())
        ->setScreenshotType('jpeg', 100)
        ->setDelay(3000)
        //->screenshot()
        ->waitForFunction("snapshotDone == true", 1000, 2000)
        ->save($path. "ad.jpeg")
    ;

I have added delay so that the function inside for chartjs finishes. I tried using waitForFunction but I'm not sure I get the documentation. Can anyone help?


Solution

  • you can call your site locally and it will be with a chart

    protected function getChartImage($html, $imagePath = 'chart.png') {
        Browsershot::url('http://namesite.test/namedetails/adam/')->save($imagePath);
        return $imagePath;
    }
    

    example of chart