I was not happy with any of these solutions due to the following issues:
- My tag labels are not on canvas
- My axis labels are not on canvas
- Saving Firefox with canvas2image is confusing for the average user
My solution to this problem is to change the parameters for the chart so that they can be moved as soon as the canvas, then use canvas-to-blob to convert this chart to blob and then FileSaver to save the blob for the user, finally I replace the graph after saving the image.
The following JS plugins are required:
the 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 problems regarding the above solutions, you can try this.
srussking
source share