Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating an SVG DOM element from a String

Tags:

javascript

svg

How would I go about creating an SVG DOM element from a String?

Example:

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>'; 
like image 402
nicholaswmin Avatar asked Jun 08 '14 14:06

nicholaswmin


People also ask

Is SVG a DOM element?

SVG is a language for describing 2D graphics in XML. Canvas draws 2D graphics, on the fly (with a JavaScript). SVG is XML based, which means that every element is available within the SVG DOM.

How do I make SVG text?

To create text SVG's in Inkscape you need to turn your text into a path. To do this just select your text and then go to “path” in the top menu bar and then choose “object to path”. This will turn your text into a path. From here you can click into each individual letter of your text and edit however you'd like.

What is SVG in Dom?

The SVG DOM allows attributes to be accessed even though they haven't been specified explicitly in the document markup. When this happens an appropriate object is created, initialized and returned. This newly constructed object does not affect rendering until it is modified for the first time.


1 Answers

You can use DOMParser to parse an XML string.

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

The root element for the parsed string will be doc.documentElement

For this to work properly cross-browser you'll need to set the html namespace i.e. your string will need to look like this...

var svg2='<svg xmlns="http://www.w3.org/2000/svg" width="500" height="500" ... 
like image 112
Robert Longson Avatar answered Sep 16 '22 19:09

Robert Longson