d3引入其它svg文件

如何在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 标签需要设置xywidthheight等属性。


这种方式有个局限性,引入的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);
});

报错解决

  1. 这种容易出现报错 TypeError: Failed to execute 'fetch' on 'Window': The provided value is not of type 'RequestInit'.
    在这里插入图片描述
    这是因为d3.xml方法出现了问题,有传参不正确导致的,也会有其他问题导致的。

  2. 还有中报错就是加载路径不正确,在调试时可以将svg文件放置到 public 目录下,然后用目录后的路径请求处理。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值