0

I have written a function to save the chart as image.Below i have mentioned code which i have written : HTML:

<div> <span id="save" onclick="javascript:saveChart1();"  style="height:10px;width:40px; color:#000;"> comment</span></div> 
<div id="chart_load"></div>
<div id="chart_save">
     <canvas id="chart_area" height="300px" width="415px"></canvas>
</div> 

Javescript:

function saveChart1()
{

             var outcan=document.getElementById("chart_area");
               var obj=document.getElementsByTagName("canvas");                
                var ctx=outcan.getContext("2d");        
                ctx.drawImage(obj[1],0,0);        
                html2canvas($("#chart_save"), {
                        onrendered: function(canvas) {
                    var a = document.createElement('a');
        // toDataURL defaults to png, so we need to request a jpeg, then convert for file download.
        a.href = canvas.toDataURL("image/png").replace("image/png", "image/octet-stream");
        a.download = 'ss.jpg';
        a.click();

                    }
                        });
}

When i click on save button then getting below mentioned error:

Uncaught TypeError: Failed to execute 'drawImage' on 'CanvasRenderingContext2D': The provided value is not of type '(CSSImageValue or HTMLImageElement or SVGImageElement or HTMLVideoElement or HTMLCanvasElement or ImageBitmap or OffscreenCanvas)'
    at saveChart1 (generatedContent:310)
    at HTMLSpanElement.onclick

Can any one suggest me where i am doing wrong.

sam140
  • 219
  • 1
  • 5
  • 27

1 Answers1

0

Try this

var obj = document.getElementsByTagName("canvas");
html2canvas(document.getElementById("target"), {
    onrendered: function (canvas) {
        var a = document.createElement('a');
        // toDataURL defaults to png, so we need to request a jpeg, then convert for file download.
        a.href = canvas.toDataURL("image/png").replace("image/png", "image/octet-stream");
        a.download = 'ss.jpg';
        a.click();
    }
});

Working example

Manoj
  • 4,951
  • 2
  • 30
  • 56
  • Getting below mentioned error :Uncaught TypeError: html2canvas(...).then is not a function at saveChart1 (generatedContent:302) at HTMLSpanElement.onclick (generatedContent:85) html2canvas.js:2769 Uncaught TypeError: canvas.getContext is not a function at html2canvas.js:2769 at Object._html2canvas.Renderer (html2canvas.js:2552) at Object.options.complete (html2canvas.js:2667) at start (html2canvas.js:2082) at Object._html2canvas.Preload (html2canvas.js:2368) at html2canvas.js:2678 – sam140 Jul 31 '17 at 07:44
  • You want to convert your chart into image Right? Check my updated answer – Manoj Jul 31 '17 at 07:52
  • chart is not rendering proper..for example if i want to export the bar chart as image then i am getting only x and ya axis values nothing else.even no bar is created .. – sam140 Jul 31 '17 at 08:22