Save Google charts as a image

前端 未结 4 572
刺人心
刺人心 2020-12-05 05:55

So after hours of websearching, googling and overflowing i can\'t find the solution to my problem.

I got a linechart from Google charts. I want to convert it to PNG,

4条回答
  •  无人及你
    2020-12-05 06:46

    When you visit the site, paste this in the console (overwriting the malfunctioning function).

      function getImgData(chartContainer) {
        var chartArea = chartContainer.getElementsByTagName('svg')[0].parentNode;
        var svg = chartArea.innerHTML;
        var doc = chartContainer.ownerDocument;
        var canvas = doc.createElement('canvas');
        canvas.setAttribute('width', chartArea.offsetWidth);
        canvas.setAttribute('height', chartArea.offsetHeight);
    
    
        canvas.setAttribute(
            'style',
            'position: absolute; ' +
            'top: ' + (-chartArea.offsetHeight * 2) + 'px;' +
            'left: ' + (-chartArea.offsetWidth * 2) + 'px;');
        doc.body.appendChild(canvas);
        canvg(canvas, svg);
        var imgData = canvas.toDataURL("image/png");
        canvas.parentNode.removeChild(canvas);
        return imgData;
      }
    

    In JS it was searching for an iframe bla bla to get the svg.


    To automatically save the image, you can just let the method being invoked programmatically.

    document.body.addEventListener("load", function() {
    
            saveAsImg( document.getElementById("pie_div")); // or your ID
    
        }, false );
    


    For saving images serverside, this post could be helpful save a PNG image server-side

    Update
    Posting images to PHP (index.js)

    function saveToPHP( imgdata ) {
    
        var script = document.createElement("SCRIPT");
    
        script.setAttribute( 'type', 'text/javascript' );
        script.setAttribute( 'src', 'save.php?data=' + imgdata );
    
        document.head.appendChild( script );
    }
    
    function save() {
    
        var canvas = document.getElementById("canvas"), // Get your canvas
            imgdata = canvas.toDataURL();
    
        saveToPHP( imgdata );
    }
    
    function drawOnCanvas() {
    
        var canvas = document.getElementById("canvas"), // Get your canvas
            ctx = canvas.getContext("2d");
    
        ctx.strokeStyle = "#000000";
        ctx.fillStyle = "#FFFF00";
        ctx.beginPath();
        ctx.arc(100,99,50,0,Math.PI*2,true);
        ctx.closePath();
        ctx.stroke();
        ctx.fill();
    }
    
    drawOnCanvas(); // Test
    save();
    

    save.php

    
    

提交回复
热议问题