如何在d3中引入其它svg文件,目前有两种方式。
1. 图片的方式引入
import * as d3 from 'd3';
d3.select('#target')
.append('g').
append('image'). // 从这里插入图片元素
attr('xlink:href', url) // 这里设置路径
或者
import * as d3 from 'd3';
d3.select('#target')
.append('g').
append('img'). // 从这里插入图片元素
attr('src', url) // 这里设置路径
image 标签需要设置x
、y
、width
、height
等属性。
这种方式有个局限性,引入的svg文件不能修改样式,但可以设置 defs标签 的方式重复使用。
2. 通过d3.xml方法加载
d3.xml(`/svg/file.svg`).then(res => {
const result = xml.getElementsByTagName('svg')[0];
const result2 = d3.select(result).html();
d3.select('#target')
.append('g')
.append('svg')
.attr('xmlns:xlink', 'http://www.w3.org/1999/xlink')
.attr('xmlns', 'http://www.w3.org/2000/svg')
.attr('fill', 'red')
.attr('stroke', 'blue')
.attr('viewBox', '0 0 1024 1024') // 这个参数不能少
.attr('width', 200)
.attr('width', 200)
.html(result2);
// 清除子节点的fill和stroke属性,这样可以让父级的样式属性生效
d3.select('#target').selectAll('svg')
.selectAll('*')
.attr('fill', null)
.attr('stroke', null);
}).catch(e => {
console.log(e);
});
报错解决
-
这种容易出现报错
TypeError: Failed to execute 'fetch' on 'Window': The provided value is not of type 'RequestInit'.
这是因为d3.xml方法出现了问题,有传参不正确导致的,也会有其他问题导致的。 -
还有中报错就是加载路径不正确,在调试时可以将svg文件放置到 public 目录下,然后用目录后的路径请求处理。