[Chartjs]-Print chart in Chrome build by Chart jS using javascript

1👍

The snippet below runs on JSFiddle. Remember to enable pop ups for chrome, if you want your pop ups not to get blocked by chrome have a look at this question.

function PrintImage() {
    id = 'chart';
    var canvas = document.getElementById(id);
    var win = window.open(canvas.toDataURL(), '_blank');
    
    win.document.write("<br><img src='" + canvas.toDataURL() + "'/>");
    win.print();
    win.location.reload();
}
 

function drawImage(){
    var ctx = $("canvas")[0].getContext("2d"),
        img = new Image();
    
    img.onload = function(){
        ctx.drawImage(img, 0, 0, 500, 500);
        $("span").text("Loaded.");
    };
    img.src = "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQ7udaoWuG0i57WCc7OyxkWG0jCkqMIBa7D7ff2Dk1Fk7rCsoQr";
    img.crossOrigin ="anonymous";
    $("span").text("Loading...");
}

$("#add").click(drawImage); 
$("#print").click(PrintImage);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
    <head>
        <title>Canvas Replace</title>       
    </head>

    <body>
        <button id="add">Add Image</button><span></span>
        <button id= "print">Print Image</button>
        <canvas width="500" height="500" id='chart'></canvas>
    </body>
    
    
</html>

Leave a comment