d3 - svg path react 标签的简单使用
refer: http://siwei.me/blog/posts/d3-svg-path
https://www.w3schools.com/graphics/svg_path.asp
1.安装依赖d3库
npm install d3
或
yarn add d3
2.
import React, { useEffect } from 'react';
import * as d3 from 'd3';
3.
const MyComponent = () => {
useEffect(() => {
// D3 的路径生成器
const pathGenerator = d3.path();
// 设置路径命令
pathGenerator.moveTo(50, 50);
pathGenerator.lineTo(200, 50);
pathGenerator.lineTo(200, 200);
pathGenerator.closePath();
// 创建 SVG 路径元素
const svgPath = pathGenerator.toString();
// 在控制台输出 SVG 路径字符串
console.log(svgPath);
}, []);
return <svg />;
};
4.
const MyComponent = () => {
const svgRef = useRef(null);
useEffect(() => {
// D3 的路径生成器...
// ...
// 获取 SVG 元素的引用
const svgElement = d3.select(svgRef.current);
// 添加 SVG 路径元素到 SVG 元素中
svgElement.append('path').attr('d', svgPath);
}, []);
return <svg ref={svgRef} />;
};做了一个简单的Demo:https://github.com/120821/react_learn_for_d3_svg_path_20230912