嗨,我正在尝试保存flot图为图像(png/jpeg..)。我调查了他们建议使用canvas.toDataURL("image/png");或canvas2image的其他问题。但是,我使用div作为flot,如下所示。
<div id="graph"> <div id="graphc" style="width: 600px;height:153px; top: 560px; left:120px; auto;"> </div> </div>
plot= $.plot($("#graph #graphc"),
[ {data: data5 ],
xaxis: { mode: "time",minTickSize: [10, "second"],
timeformat: "%0H:%0M" } } );
如何保存此图表?谢谢你的帮助。
发布于 2013-03-25 22:08:04
您需要获取flot在div中创建的画布。如果你看一下docs,你会看到有一个.getCanvas()
函数。或者,您可以使用jQuery在div中选择一个画布。
一旦有了画布,就可以使用.toDataURL
或任何其他技术。
所以你就有了这个:
plot= $.plot($("#graph #graphc"),
[ {data: data5 ],
xaxis: { mode: "time",minTickSize: [10, "second"],
timeformat: "%0H:%0M" } } );
然后你应该能够做到这一点:
var myCanvas = plot.getCanvas();
要真正下载文件,您需要使用.toDataURL()
,然后将image/png
mime类型替换为image/octet-stream
,然后将document.location.href
设置为您的字符串:
var image = myCanvas.toDataURL();
image = image.replace("image/png","image/octet-stream");
document.location.href=image;
或者,您可以使用canvas2image为您完成所有这些工作。
编辑:唯一的问题是,至少在FireFox中,图像将以随机的外观名称和.part
扩展名保存。将其更改为.png
将显示它是实际的图像。不确定是否有好的方法说服浏览器使用友好的名称保存它,或者至少使用正确的扩展名。
发布于 2016-06-10 04:09:25
由于以下问题,我对这些解决方案中的任何一个都不满意:
来说是令人困惑的
我对这个问题的解决方案是更改图表的选项,将图表重新绘制为仅画布图表,然后使用canvas- to -blob将此图表转换为blob,然后使用FileSaver为用户保存blob,最后在保存图像后重新绘制图表。
需要以下JS插件:
代码:
//set data array, and options
$('a.download_as_img').click(function(e){
e.preventDefault();
saveAsImage(graph_selector, data, options, xaxis,yaxis)
})
function saveAsImage(graph_selector, data_arr, options, xaxis, yaxis){
var canvas = replotChartAsCanvas(graph_selector, data_arr, options, xaxis, yaxis);
var title = 'chart';// or some jquery way to get your title or w/e
canvas.toBlob(function(blob) {
saveAs(blob, title + ".png");
});
//convert back to normal
var plot = $.plot(graph_selector, data_arr, options);
}
//helper for saveAsImage
// returns canvas
function replotChartAsCanvas(graph_selector, data_arr, options, xaxis, yaxis){
//change canvas options to true and replot
var canvas_options = {
canvas: true,
axisLabels: {
show: true
},
xaxes: [
{
axisLabelUseCanvas: true,
axisLabel: xaxis
}
],
yaxes: [
{
axisLabelUseCanvas: true,
position: 'left',
axisLabel: yaxis
}
]
}
var merged_opts = {}
$.extend(merged_opts, options, canvas_options); //done this way to ensure canvas_options take priority
var plot = $.plot(graph_selector, data_arr, merged_opts);
return plot.getCanvas();
}
如果您对上面的解决方案有类似的顾虑,您可以尝试这个解决方案。
发布于 2013-03-28 22:26:54
我在代码上做了一些修改。为了在本地保存图形,你可以使用下面的代码。
var plot= $.plot($("#graph #graphc"),
[ {data: data5 ],
xaxis: { mode: "time",minTickSize: [10, "second"],
timeformat: "%0H:%0M" } } );
var myCanvas = plot.getCanvas();
var image = myCanvas.toDataURL("image/png").replace("image/png", "image/octet-stream"); /// here is the most important part because if you dont replace you will get a DOM 18 exception.
document.location.href=image;
https://stackoverflow.com/questions/15616925
复制相似问题