如何在SVG.js的contactUs.svg()中添加多路径及g标签?
问题:如何在同一SVG容器中添加多个path及g标签
我已经写了下面的函数,用来给c-contact-address类添加SVG,现在能成功添加单个path,但不知道怎么在同一个SVG里加多个path和g标签,求解决。
const contactUsSvg = () => { const contactUs = SVG(); contactUs.addClass("c-contact-address").viewbox(0, 0, 1513.1, 619.1); contactUs.svg( '<path class="c-contact-address-path" d="M1.5 157.7c37.3-43.3 99-64.1 154.9-52S259.9 162.1 275.9 217c7.2 24.7 8.1 52.1-2.9 75.3-11.1 23.2-35.9 40.7-61.4 38.2-14.8-1.4-30.9-17.2-22.2-29.2 2.4-3.3 6.1-5.3 9.8-7 13.2-5.8 28.2-8 42.2-4.7 40.5 9.6 56.8 56.7 74.7 94.3 42.4 89 127.7 152.7 221 184.7 108.8 37.2 243.1 42 355.5 20.7 61.7-11.7 139.8-20.2 185.2-67 27.9-28.8 72.9-109.6 70.9-197.4" fill="none" stroke="#dde5ed" stroke-width="3.022" stroke-linecap="round" stroke-linejoin="round" style="stroke-dashoffset: 0; stroke-dasharray: none;"></path>' ); };
解决方案
有两种实用方法可以实现需求:
方法1:直接在svg()方法中传入多元素组合字符串
把多个path、g标签拼接成完整的SVG片段字符串,直接传给contactUs.svg()即可,示例如下:
const contactUsSvg = () => { const contactUs = SVG(); contactUs.addClass("c-contact-address").viewbox(0, 0, 1513.1, 619.1); contactUs.svg(` <g class="c-contact-address-group"> <path class="c-contact-address-path" d="M1.5 157.7c37.3-43.3 99-64.1 154.9-52S259.9 162.1 275.9 217c7.2 24.7 8.1 52.1-2.9 75.3-11.1 23.2-35.9 40.7-61.4 38.2-14.8-1.4-30.9-17.2-22.2-29.2 2.4-3.3 6.1-5.3 9.8-7 13.2-5.8 28.2-8 42.2-4.7 40.5 9.6 56.8 56.7 74.7 94.3 42.4 89 127.7 152.7 221 184.7 108.8 37.2 243.1 42 355.5 20.7 61.7-11.7 139.8-20.2 185.2-67 27.9-28.8 72.9-109.6 70.9-197.4" fill="none" stroke="#dde5ed" stroke-width="3.022" stroke-linecap="round" stroke-linejoin="round"></path> <path class="c-contact-address-path" d="M100 100 L200 200 L300 100 Z" fill="none" stroke="#dde5ed" stroke-width="3.022"></path> <!-- 可继续添加更多path或其他SVG元素 --> </g> `); };
方法2:使用SVG.js API链式创建元素
这种方式更灵活,能精准控制每个元素的属性,适合后期需要动态修改的场景:
const contactUsSvg = () => { const contactUs = SVG(); contactUs.addClass("c-contact-address").viewbox(0, 0, 1513.1, 619.1); // 创建g标签容器 const addressGroup = contactUs.group().addClass("c-contact-address-group"); // 向g容器添加第一个path addressGroup.path('M1.5 157.7c37.3-43.3 99-64.1 154.9-52S259.9 162.1 275.9 217c7.2 24.7 8.1 52.1-2.9 75.3-11.1 23.2-35.9 40.7-61.4 38.2-14.8-1.4-30.9-17.2-22.2-29.2 2.4-3.3 6.1-5.3 9.8-7 13.2-5.8 28.2-8 42.2-4.7 40.5 9.6 56.8 56.7 74.7 94.3 42.4 89 127.7 152.7 221 184.7 108.8 37.2 243.1 42 355.5 20.7 61.7-11.7 139.8-20.2 185.2-67 27.9-28.8 72.9-109.6 70.9-197.4') .addClass("c-contact-address-path") .fill("none") .stroke({ color: "#dde5ed", width: 3.022, linecap: "round", linejoin: "round" }); // 向g容器添加第二个path addressGroup.path('M100 100 L200 200 L300 100 Z') .addClass("c-contact-address-path") .fill("none") .stroke({ color: "#dde5ed", width: 3.022 }); // 也可直接向根SVG容器添加元素(无需经过g标签) contactUs.path('M500 500 L600 600 L700 500 Z').addClass("c-contact-address-path"); };
内容的提问来源于stack exchange,提问作者Ipper Balaji
相关产品推荐
相关产品推荐

