I wasn't happy with any of these solutions due to the following problems:
- My tick labels are not on the canvas
- My axis labels are not on the canvas
- Firefox saving with canvas2image is confusing for a normal user
My solution to this problem is to change the options for the chart to replot as canvas only chart, then use canvas-to-blob to convert this chart to a blob, then FileSaver to save the blob for the user, finally I replot the chart after saving the image.
Requires the following JS plugins:
Code:
//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();
}
Perhaps if you have similar concerns about the above solution(s), you can try this one.