【问题标题】:unable to save chart as image无法将图表另存为图像
【发布时间】:2018-01-06 15:58:42
【问题描述】:

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

JavaScript:

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

谁能建议我哪里做错了。

【问题讨论】:

  • 你能提供一个关于 jsfiddle 或 codepen.io 的工作示例吗?
  • 你不应该使用obj[0]吗?
  • @ArnoldSchrijver: 如果我使用 obj[0] 那么我得到的是空白图像?
  • @Difster:我为此创建了 jsfiddle:jsfiddle.net/sam140/0b7omvcx/1

标签: jquery canvas html5-canvas canvg


【解决方案1】:

试试这个

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

【讨论】:

  • 得到下面提到的错误:Uncaught TypeError: html2canvas(...).then is not a function at saveChart1 (generatedContent:302) at HTMLSpanElement.onclick (generatedContent:85) html2canvas.js:2769 Uncaught TypeError:canvas.getContext 不是 html2canvas.js:2769 处 Object._html2canvas.Renderer (html2canvas.js:2552) 处 Object.options.complete (html2canvas.js:2667) 处的函数 (html2canvas.js:2082)在 Object._html2canvas.Preload (html2canvas.js:2368) 在 html2canvas.js:2678
  • 您想将您的图表转换为图像,对吧?检查我的更新答案
  • 图表渲染不正确..例如,如果我想将条形图导出为图像,那么我只会得到 x 和 ya 轴值。即使没有创建条形..
猜你喜欢
  • 2019-07-17
  • 2016-07-18
  • 1970-01-01
  • 2012-03-24
  • 1970-01-01
  • 2014-05-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多