获取svg标签属性

74 阅读1分钟
 // 假设我们有一个包含SVG标签的字符串
    var svgString = '<svg><line x1="59280.828125" y1="33251.5546875" x2="62851.9765625" y2="30605.84375"></line></svg>';
 // 使用DOMParser来解析字符串中的SVG标签
    var parser = new DOMParser();
    var svgDoc = parser.parseFromString(svgString, "text/xml");
 // 获取SVG标签
    var svgElement = svgDoc.getElementsByTagName("svg")[0];
    var svgChild = svgElement.children[0];
    console.dir(svgChild.tagName, "svgChild");
 // 获取SVG的属性
 // attributes
    var x1 = svgChild.getAttribute("x1");
    var y1 = svgChild.getAttribute("y1");
    var x2 = svgChild.getAttribute("x2");
    var y2 = svgChild.getAttribute("y2");
 // 打印属性
    console.log("x1:", x1);
    console.log("y1:", y1);
    console.log("x2:", x2);
    console.log("y2:", y2);