javascript - 将 JavaScript 生成的 SVG 转换为文件

标签 javascript css svg d3.js

我正在使用 d3.js 来可视化一些数据。我希望能够获取它生成的 SVG 代码并将其存储为 .svg 图像文件(用于在 Inkscape/Illustrator 中进行编辑)。

我试过简单地复制 svg 标签的内容,即

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

放入名为 image.svg 的文件中,但这会遗漏颜色/样式信息,这些信息位于两个单独的 CSS 文件中。

我正在使用 this example .

有没有简单的方法可以做到这一点?

最佳答案

这是使用 svg-crowbar.js 的好方法在您的站点上提供一个按钮,以允许您的用户将您的可视化文件下载为 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 的进一步观察:

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 下载。

注意: svg-crowbar.js 是从 https://rawgit.com 加载的或 http://nytimes.github.com ;您可能更愿意将其集成到您的网站/文件夹中。

关于javascript - 将 JavaScript 生成的 SVG 转换为文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8435537/

相关文章:

javascript - Google Maps API v3 添加带有自定义文本的信息窗口的多个标记

html - bootstrap hidden-xs 不工作

javascript - 在 html 表的一列中合并 <td> 行

javascript - Owl Carousel 不工作,没有错误,div 消失了

haskell - 带有反射 frp 的单个 svg 元素

javascript - 尝试创建大量变量和 for 循环是行不通的

javascript - 动态修改 JavaScript 中的构造函数?

javascript - CodeMirror 和括号,带有 CSS 快速编辑的自定义模式

css - 手机上的图标字体显示问题

javascript - 如何缩放 D3 气泡图中的文本