Skip to content Skip to sidebar Skip to footer

How To Add A Data-* Attribute To Svg On Or After Creation

I have a canvas that I am creating a snapshot from and saving and downloading as an svg using the FileSaver.js api. The svg never gets rendered to the app, it is directly downloade

Solution 1:

The best would be to do it in the this.getFrame() method. This method will certainly create a parsed SVG document, before returning its serialization to string. From this parsed SVG doc will you add this attribute.

Speculative partial content of getFrame

getFrame: function() {
  var svg = document.createElementNS(svgNS, 'svg');
  svg.dataset.settings = your_data; // here you set the data attribute// ... append a lot of elements to svg to generate the svg image// ...returnnewXMLSerializer().serializeToString(svg); // return the markup
}

Now, since you didn't provided this getFrame method, I will assume you didn't made it, and that it may be hard for you to tweak it.

So one way, after you've got the markup, is to re-parse this markup, add your attribute, and re-serialize it again...

var svgStr = /*this.*/getFrame(); // get the markup// (re-)parse this string as an SVG docvar svgDoc = newDOMParser().parseFromString(svgStr, 'image/svg+xml');
// set your attribute
svgDoc.documentElement.dataset.settings = "foo-bar";
// re-serialize
svgStr = newXMLSerializer().serializeToString(svgDoc.documentElement);
// save the modified markupsaveAs(newBlob([svgStr], {type:'image/svg+xml'}));



functiongetFrame(){
  return`<svg width="120" height="120" viewBox="0 0 120 120"
    xmlns="http://www.w3.org/2000/svg">
  <rect x="10" y="10" width="100" height="100"/>
  <script>
  alert(document.documentElement.dataset.settings);
  <\/script>
</svg>`
}
// for demo displays in an <object> instead of savingfunctionsaveAs(blob){
  var obj = document.createElement('object');
  obj.data=  URL.createObjectURL(blob);
  document.body.appendChild(obj);
}

Post a Comment for "How To Add A Data-* Attribute To Svg On Or After Creation"