0

我已经编写了一个将图表保存为图像的函数。下面我提到了我编写的代码: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> 

文案:

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();

                    }
                        });
}

当我点击保存按钮然后得到下面提到的错误:

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

任何人都可以建议我在哪里做错了。

4

1 回答 1

0

尝试这个

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();
    }
});

工作示例

于 2017-07-31T07:42:40.013 回答