Skip to content

Instantly share code, notes, and snippets.

@jkawamoto
Created May 16, 2016 23:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jkawamoto/657be368dbec2e8750a50e071789bc29 to your computer and use it in GitHub Desktop.
Save jkawamoto/657be368dbec2e8750a50e071789bc29 to your computer and use it in GitHub Desktop.
Download a SVG element as a PNG file.
#
# save-fig.coffee
#
# Copyright (c) 2016 Junpei Kawamoto
#
# This software is released under the MIT License.
#
# http://opensource.org/licenses/mit-license.php
#
$ = require "jquery"
# Encode data.
#
# @param data [Object] an object to be encoded.
# @return [String] encoded string.
encode = (data)->
btoa(unescape(encodeURIComponent(data)))
# Save a figure.
#
# @param id [String] an ID of SVG element.
# @return [Promise] promise object to be fulfiled after cleaning up.
module.exports = (id) ->
new Promise (resolve) ->
# Initialize
svg = $ id
width = svg.width()
height = svg.height()
$("body").append """
<canvas id="result-canvas" class="hidden"
width="#{width}" height="#{height}">
</canvas>
"""
canvas = $ "#result-canvas"
.get 0
ctx = canvas.getContext "2d"
old_width = svg.attr "width"
old_height = svg.attr "height"
svg.attr "width", width
svg.attr "height", height
svg.attr "viewBox", "0 0 #{width} #{height}"
svgData = new XMLSerializer().serializeToString svg.get(0)
imgsrc = "data:image/svg+xml;charset=utf-8;base64,#{encode svgData}"
image = new Image()
image.onload = ->
ctx.fillStyle = "white"
ctx.fillRect 0, 0, width, height
ctx.drawImage image, 0, 0
$("body").append """
<a id="image-file" class="hidden" type="application/octet-stream"
href="#{canvas.toDataURL("image/png")}" download="graph.png">
Donload Image
</a>
"""
$("#image-file").get 0
.click()
# Clean up
$("#result-canvas").remove()
$("#image-file").remove()
svg.attr "width", old_width
svg.attr "height", old_height
resolve()
image.src = imgsrc
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment