从String创建SVG DOM元素

时间:2014-06-08 14:48:05

标签: javascript svg

我如何从String创建一个SVG DOM元素?

示例:

var svgStr = '<svg width="500" height="400" xmlns="http://www.w3.org/2000/svg"><!-- Created with Method Draw - http://github.com/duopixel/Method-Draw/ --><g><title>background</title><rect fill="#fff" id="canvas_background" height="402" width="502" y="-1" x="-1"/><g display="none" overflow="visible" y="0" x="0" height="100%" width="100%" id="canvasGrid"><rect fill="url(#gridpattern)" stroke-width="0" y="0" x="0" height="100%" width="100%"/></g></g><g><title>Layer 1</title><path id="svg_1" d="m118,242l64,-153l63,157c0,0 45,-71 49,-68c4,3 11,146 12,146c1,0 -173,-7 -173,-7c0,0 -61,-72 -61,-72c0,0 110,-156 46,-3z" fill-opacity="0.7" stroke-width="2" stroke="#995757" fill="#995757"/></g></svg>';

4 个答案:

答案 0 :(得分:24)

您可以使用DOMParser来解析XML字符串。

var parser = new DOMParser();
var doc = parser.parseFromString(stringContainingXMLSource, "image/svg+xml");

解析后的字符串的根元素是doc.documentElement

为了使其能够跨浏览器正常工作,您需要设置html命名空间,即您的字符串需要看起来像这样...

var svg2='<svg xmlns="http://www.w3.org/2000/svg" width="500" height="500" ...

答案 1 :(得分:9)

假设您使用的是JavaScript,您只需将该字符串作为通过DOM API获取的现有元素的innerHTML传递:

var svg2 = "<svg ...> ... </svg>";
var container = document.getElementById("container");
container.innerHTML = svg2;

请参阅: JSFiddle

答案 2 :(得分:1)

在HTML中读取和编写SVG的innerHTML似乎运行良好,除了在Internet Explorer(9-11)中:http://cs.sru.edu/~ddailey/svg/IframeSVG.htm。如果需要IE兼容性(如真实Web应用程序),则使用DOM方法创建合适的容器(对象,iframe或嵌入),并通过该容器内的DOM方法一次构建一个SVG,一个childNode。这是一件苦差事,但http://www.w3.org/Graphics/SVG/IG/resources/svgprimer.html#SVG_HTML涵盖了基础知识。

答案 3 :(得分:1)

我正在构建SVG图表,需要使用户能够传递任何SVG并将其制作为图表注释。解决方案是:

index.html -我要将子SVG附加到的根SVG元素

<svg id="chart_SVG" width="900" height="600" role="img" xmlns="http://www.w3.org/2000/svg"></svg>

api.ts -用于添加注释的API(以TypeScript编写)。 x,y-协调放置注释的位置

function drawAnnotation(x: number, y: number, svgContent: string, svgId: string): SVGElement {
  const svgRoot = document.getElementById("chart_SVG");
  const svgNode = document.createRange().createContextualFragment(svgString);
  svgRoot.appendChild(svgNode);
  const newNode = this.svgRoot.lastChild as SVGElement;
  newNode.id = svgId;
  newNode.setAttribute("x", x.toString());
  newNode.setAttribute("y", y.toString());
  return newNode;
}

example.ts

drawAnnotation(
  100,
  100,
  '<svg><g><rect x="0" y="0" width="100%" height="100%" stroke="red" stroke-width="10" fill="orange"/><text x="50%" y="50%" dominant-baseline="middle" text-anchor="middle" font-family="Verdana" font-size="24" fill="blue">TEXT</text></g></svg>',
  "myNewNode"
)
相关问题