Created
February 24, 2017 12:53
-
-
Save tewson/a34f73cef234b3d27c45acf1991f8707 to your computer and use it in GitHub Desktop.
A simple script demonstrating how to generate an SVG file from the DOM.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<body> | |
<div id="chart"> | |
<svg width="100" height="100"> | |
<circle cx="50" cy="50" r="40" stroke="black" stroke-width="1" fill="white" /> | |
</svg> | |
</div> | |
<button id="download">Download</button> | |
<script> | |
document.getElementById('download').onclick = function () { | |
var chartElement = document.querySelector('#chart > svg'); | |
var serializer = new XMLSerializer(); | |
var source = serializer.serializeToString(chartElement); | |
source = '<?xml version="1.0" standalone="no"?>\r\n' + source; | |
var downloadUri = 'data:image/svg+xml;charset=utf-8,' + encodeURIComponent(source); | |
var downloadLink = document.createElement('a'); | |
downloadLink.download = 'circle.svg'; | |
downloadLink.href = downloadUri; | |
document.body.appendChild(downloadLink); | |
downloadLink.click(); | |
document.body.removeChild(downloadLink); | |
delete downloadLink; | |
}; | |
</script> | |
</body> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment