如何从SVG路径字符串中高效提取坐标并存储为数组?
高效提取SVG路径坐标到数组的实现方法
核心思路
先从SVG字符串中精准提取出路径数据(即d属性的内容),再从中抓取所有数字坐标,最后按x、y成对的规则拆分到两个数组中。
具体代码实现
// 原始SVG路径字符串 let path_string='<path transform="matrix(1,0,0,-1,0,600)" stroke-width=".074" stroke-linecap="round" stroke-linejoin="round" fill="none" stroke="#000000" d="M 274.75 301.4 L 275.41 303.36 L 275.41 307.28 L 289.11 293.57 "/>' // 1. 提取d属性的路径内容 const dMatch = path_string.match(/d="([^"]+)"/); if (!dMatch) { console.error("未找到SVG路径的d属性"); } const dContent = dMatch[1]; // 2. 提取所有坐标数字(如需兼容负坐标,把正则改成 /-?\d+\.?\d*/g 即可) const allCoords = dContent.match(/\d+\.?\d*/g).map(numStr => parseFloat(numStr)); // 3. 拆分x、y坐标数组 const x_coor_arr = []; const y_coor_arr = []; allCoords.forEach((coord, index) => { index % 2 === 0 ? x_coor_arr.push(coord) : y_coor_arr.push(coord); }); // 输出结果 console.log(`x_coor_arr=[${x_coor_arr.join(',')}];`); console.log(`y_coor_arr=[${y_coor_arr.join(',')}];`);
代码说明
- 提取d属性:用正则
/d="([^"]+)"/直接匹配d="和闭合双引号之间的内容,跳过SVG标签里的其他冗余属性,一步定位核心数据。 - 提取坐标数字:正则
/\d+\.?\d*/g可以匹配所有正整数和小数,遇到负坐标时只需在正则开头加-?即可兼容。 - 拆分数组:SVG路径的坐标天生是x、y成对出现的,通过索引奇偶性直接拆分,逻辑简单高效,时间复杂度为O(n)(n为坐标总数)。
内容的提问来源于stack exchange,提问作者Buzz Su
相关产品推荐
相关产品推荐

