在使用D3.js(IE,safari和chrome)创建SVG之后,如何保存/导出SVG文件? [英] How do I save/export an SVG file after creating an SVG with D3.js (IE, safari and chrome)?

查看:362
本文介绍了在使用D3.js(IE,safari和chrome)创建SVG之后,如何保存/导出SVG文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前有一个使用D3的网站,我希望用户可以选择将SVG保存为SVG文件。我使用crowbar.js做到这一点,但它只适用于chrome。 Safari不会发生任何事情,IE会拒绝在crowbar.js中使用的 click()方法下载文件。

I currently have a website using D3 and I'd like the user to have the option to save the SVG as an SVG file. I'm using crowbar.js to do this, but it only works on chrome. Nothing happens of safari and IE gives an access denied on the click() method used in crowbar.js to download the file.

var e = document.createElement('script'); 

if (window.location.protocol === 'https:') { 
    e.setAttribute('src', 'https://raw.github.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);

如何在safari,IE和chrome中下载基于SVG元素的SVG文件?

How do I download an SVG file based on the SVG element on my website in safari, IE and chrome?

推荐答案

有5个步骤。我经常使用这个方法输出内联svg。

There are 5 steps. I often use this method to output inline svg.


  1. 获取inline svg元素输出。


  2. 通过encodeURIComponent方法构造svg的url数据方案。
  3. 通过XMLSerializer方法来创建svg的URL数据方案。
  4. 将此网址设置为某个a元素的href属性,右键点击此链接即可下载svg文件。

  1. get inline svg element to output.
  2. get svg source by XMLSerializer.
  3. add name spaces of svg and xlink.
  4. construct url data scheme of svg by encodeURIComponent method.
  5. set this url to href attribute of some "a" element, and right click this link to download svg file.







//get svg element.
var svg = document.getElementById("svg");

//get svg source.
var serializer = new XMLSerializer();
var source = serializer.serializeToString(svg);

//add name spaces.
if(!source.match(/^<svg[^>]+xmlns="http\:\/\/www\.w3\.org\/2000\/svg"/)){
    source = source.replace(/^<svg/, '<svg xmlns="http://www.w3.org/2000/svg"');
}
if(!source.match(/^<svg[^>]+"http\:\/\/www\.w3\.org\/1999\/xlink"/)){
    source = source.replace(/^<svg/, '<svg xmlns:xlink="http://www.w3.org/1999/xlink"');
}

//add xml declaration
source = '<?xml version="1.0" standalone="no"?>\r\n' + source;

//convert svg source to URI data scheme.
var url = "data:image/svg+xml;charset=utf-8,"+encodeURIComponent(source);

//set url value to a element's href attribute.
document.getElementById("link").href = url;
//you can download svg file by right click menu.

这篇关于在使用D3.js(IE,safari和chrome)创建SVG之后,如何保存/导出SVG文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆