0

If I programatically create an SVG element, can I programatically save that element as an image?

Solutions I've researched on Stackoverflow and Google so far:

  • Have the user right-click-save-as

  • 3rd party libs can convert svg commands to canvas commands and save the canvas with canvas.toDataURL

Is there a direct way of programatically converting SVG to an image?

Example Javascript/SVG:

var svgns="http://www.w3.org/2000/svg";
var xlink='http://www.w3.org/1999/xlink'

var svg=document.createElementNS(svgns,"svg");
svg.setAttribute('width', 100);
svg.setAttribute('height', 100);

var e=document.createElementNS(svgns,"rect");
e.setAttribute("fill","skyblue");
e.setAttribute("stroke","lightgray");
e.setAttribute("stroke-width",4);
e.setAttribute("x",20);
e.setAttribute("y",20);
e.setAttribute("width",50);
e.setAttribute("height",50);
svg.appendChild(e);

document.body.appendChild(svg);
JustAsking
  • 157
  • 1
  • 10
  • possible duplicate of [Convert SVG to image (JPEG, PNG, etc.) in the browser](http://stackoverflow.com/questions/3975499/convert-svg-to-image-jpeg-png-etc-in-the-browser) – Robert Longson Apr 18 '14 at 18:58
  • @RobertLongson, I've researched the link you mention (and other SO/Google links) and I also know about exporting with html canvas, but my question is instead about a more direct method of creating an image from an SVG element. I'm fine with "No" as an answer, but I'm hoping to tap into more experienced minds than mine for a more direct alternative. :-) – JustAsking Apr 18 '14 at 19:11
  • have you tried a data-url? Btw, "programmatically save on client pc" is never working, you *need* the user to interact. – Bergi Apr 18 '14 at 19:16
  • @Bergi Hi! I was hoping to be able to create SVG based on user actions and save that dynamically created SVG as an image. I'm ok with any confirmation needed by the user to do the conversion. (no security violations intended!) I'm getting the impression that SVG cannot be directly programatically saved as an image. True? – JustAsking Apr 18 '14 at 21:11
  • If you are asking if there is a built-in JS function that takes an SVG element and saves it as a PNG, JPEG etc, then the answer is no. – Paul LeBeau Apr 19 '14 at 13:18
  • So the "right-click-save-as" would be working, but you want a way to open the save/download dialogue programmatically? – Bergi Apr 19 '14 at 13:44
  • @Bergi, I'm fine with using "right-click-save-as"--it works and users seem to know how to do it. But with my question I'm just trying to find out if there is an alternative method of converting SVG to an image object. (Other than right-click-save-as and drawing SVG into a canvas and canvas.toDataURL). Thanks for your help! – JustAsking Apr 19 '14 at 22:31

0 Answers0