I have a canvas and need to save it to the local disk. AFAIK writing to disk is not possible by Javascript. Therefore I consider saving the canvas on the server (I know how to do this) and automatically initiate a download as described here: How to Automatically Start a Download in PHP? Is there a more straight-forward solution for this procedure?
Asked
Active
Viewed 467 times
1 Answers
1
Yes, you can create image downloads on the client side now. The browser handles the interaction with the client's filesystem. There is a library called download.js which makes the process easy.
var data = canvas.toDataURL();
var fileName = "myCoolPicture.png";
var strMimeType = 'image/png';
download(data, fileName, strMimeType);
How to get a dataURI from an SVG image
function getSVGDataURL(svg){
return "data:image/svg+xml;utf8,"+svg.outerHTML;
}
var svg = document.getElementById('svg');
var dataurl = getSVGDataURL(svg);

I wrestled a bear once.
- 22,983
- 19
- 69
- 116
-
Thanks for the quick response. That would be really great! However the user needs to be prompted for location and filename. How can this be done? – Sempervivum Nov 11 '16 at 16:39
-
@Sempervivum - It works the same way that PHP does it. It just sends the header that tells the browser to save the file to disk, the browser then prompts the user to choose a location at which point most systems allow user to change the filename. Alternatively you caould just get the filename from the user with JS and then pass it to the funciton. – I wrestled a bear once. Nov 11 '16 at 16:46
-
That's really great and exactly what I need. However in the meantime I found out that my image is not canvas but SVG (a Highcharts graph). Does toDataURL work for SVG too? – Sempervivum Nov 11 '16 at 16:49
-
Sorry for the inconvenience, at first I was quite shure that Highcharts provides the chart as canvas. Your update works perfectly, thanks again. I tried to upvote you answer but the forum didn't accept is as my reputation level is too low. – Sempervivum Nov 11 '16 at 18:53
-
@Sempervivum - It's not inconvenient for me, but it will be inconvenient for people Googling for "how to save canvas to a file" and end up here only to find the answer is for SVG and not canvas :) if this did answer your question tho please hit the check box to the left of the answer. happy coding :) – I wrestled a bear once. Nov 11 '16 at 18:58