Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
347 views
in Technique[技术] by (71.8m points)

css - Convert JavaScript-generated SVG to a file

I am using d3.js to visualize some data. I would like to be able to take the SVG code that it generates and store it as a .svg image file (for editing in Inkscape/Illustrator).

I have tried simply copying the contents of the svg tag i.e.

<svg>
<!--snip-->
</svg>

into a file called image.svg, but this misses out on the color/styling information, which is in two separate CSS files.

I'm working with this example.

Is there a simple way to do this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Here's a nice way to use svg-crowbar.js to provide a button on your site to allow your users to download your visualization as svg.

1) Define your button's CSS:

.download { 
  background: #333; 
  color: #FFF; 
  font-weight: 900; 
  border: 2px solid #B10000; 
  padding: 4px; 
  margin:4px;
}

2) Define your button's HTML/JS:

<i class="download" href="javascript:(function () { var e = document.createElement('script'); if (window.location.protocol === 'https:') { e.setAttribute('src', 'https://rawgit.com/NYTimes/svg-crowbar/gh-pages/svg-crowbar.js'); } else { e.setAttribute('src', 'http://nytimes.github.com/svg-crowbar/svg-crowbar.js'); } e.setAttribute('class', 'svg-crowbar'); document.body.appendChild(e); })();"><!--?--><big>?</big> Download</i>

Here's a closer look at that same javascript:

javascript:(function (){ 
    var e = document.createElement('script'); 
    if (window.location.protocol === 'https:') { 
        e.setAttribute('src', 'https://rawgit.com/NYTimes/svg-crowbar/gh-pages/svg-crowbar.js'); 
    } else { 
        e.setAttribute('src', 'http://nytimes.github.com/svg-crowbar/svg-crowbar.js'); 
    } 
    e.setAttribute('class', 'svg-crowbar'); 
    document.body.appendChild(e); 
})();

3) You're done. This produces an svg download that Inkscape can open.

Note: svg-crowbar.js is loaded from https://rawgit.com or http://nytimes.github.com; you may prefer to integrate it into your website/folder.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...