const getPathLen = (d) => {
try {
const path = document.createElementNS('http://www.w3.org/2000/svg', 'path');
path.setAttribute('d', d);
const pathLen = path?.getTotalLength();
const point = path?.getPointAtLength(pathLen / 2);
return { point, pathLen };
} catch (e) {
return { point: null };
}
};
const ModalChart = () => {
const data = [
{
path: 'M0,0 C100,15 200,200 600,20',
dur: 4,
begin: 1,
pathId:' id-a',
text: '1',
stroke: 'red',
strokeWidth: 1,
x:0,
y:0
},
{
path: 'M600,20 C700,600 800,700 800,40',
dur: 5,
begin: 5,
pathId: ' id-b',
text: '2',
stroke: 'yellow',
strokeWidth: 1,
x:600,
y:20
},
{
path: 'M800,40 Q400,400 250,300',
dur: 5,
begin: 10,
pathId:' id-c',
text: '3',
stroke: 'skyblue',
strokeWidth: 1,
x:800,
y:40
},
];
return (
<div>
<svg width="100%" height="100%" >
{data.map((item, index) => {
const len = getPathLen(item.path)?.pathLen;
return (
<g key={index}>
<path
d={item.path}
id={item.pathId}
stroke="black"
strokeWidth={item.strokeWidth}
fill="none"
/>
<text fontSize={30}>
{item.text}
<animateMotion begin={`${item.begin}s`} dur={`${item.dur}s`} className={'aaa'}>
<mpath href={`#${item.pathId}`} />
</animateMotion>
</text>
<path
d={item.path}
stroke={item.stroke}
strokeWidth={3}
fill="none"
strokeDashoffset={len}
strokeDasharray={`${len},${len}`}
>
<animate
attributeName="stroke-dashoffset"
values={`${len};0`}
begin={`${item.begin}s`}
dur={`${item.dur}s`}
repeatCount="1"
/>
</path>
</g>
);
})}
</svg>
</div>
);
};
export default ModalChart;
给了初始坐标,看看运动后2的坐标
这个初值需要符合一定条件的,条件不符合导致出现偏移