使用 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)?

查看:27
本文介绍了使用 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. 获取要输出的内联 svg 元素.
  2. 通过 XMLSerializer 获取 svg 源.
  3. 添加 svg 和 xlink 的命名空间.
  4. 通过encodeURIComponent方法构建svg的url数据方案.
  5. 将此 url 设置为某些a"元素的 href 属性,然后右键单击此链接以下载 svg 文件.

<小时>

//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"?>
' + 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天全站免登陆