将 JavaScript 生成的 SVG 转换为文件 [英] Convert JavaScript-generated SVG to a file
问题描述
我正在使用 d3.js 来可视化一些数据.我希望能够获取它生成的 SVG 代码并将其存储为 .svg
图像文件(用于在 Inkscape/Illustrator 中进行编辑).
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).
我尝试简单地复制 svg 标签的内容,即
I have tried simply copying the contents of the svg tag i.e.
<svg>
<!--snip-->
</svg>
进入一个名为 image.svg 的文件,但这会遗漏颜色/样式信息,该信息位于两个单独的 CSS 文件中.
into a file called image.svg, but this misses out on the color/styling information, which is in two separate CSS files.
我正在使用这个例子.
有没有简单的方法可以做到这一点?
Is there a simple way to do this?
推荐答案
这是使用 svg 的好方法-crowbar.js 在您的网站上提供一个按钮,允许您的用户将您的可视化下载为 svg.
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) 定义按钮的 CSS:
.download {
background: #333;
color: #FFF;
font-weight: 900;
border: 2px solid #B10000;
padding: 4px;
margin:4px;
}
2) 定义按钮的 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>
以下是对同一个 javascript 的仔细观察:
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) 大功告成.这会生成一个 Inkscape 可以打开的 svg 下载.
3) You're done. This produces an svg download that Inkscape can open.
注意: svg-crowbar.js 从 https://rawgit.com 加载或 http://nytimes.github.com;您可能更愿意将其集成到您的网站/文件夹中.
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.
这篇关于将 JavaScript 生成的 SVG 转换为文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!