Embed SVG String in Dom?

I have a javascript variable that basically looks like this:

my_svg_image = '<circle cx="227.58331298828125" cy="102" r="3" style="fill:black;stroke-width:0" />'; 

It was downloaded from my database. Is there a way I can parse this line and add it to the DOM with Javascript? I have setup svgweb, but I donโ€™t see how I can get it to parse this line. Are there any other libraries that can help?

+4
source share
2 answers

Have you tried the javascript innerHTML property?

edit: you can use the innerHTML property for html elements, so you can use a string containing the whole svg image to add it to the html element. But you cannot add an svg element to an existing svg element.

Example:

 <?xml version="1.0" encoding="UTF-8"?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1 plus MathML 2.0 plus SVG 1.1//EN" "http://www.w3.org/2002/04/xhtml-math-svg/xhtml-math-svg.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:svg="http://www.w3.org/2000/svg"> <head> <meta http-equiv="Content-Type" content="application/xhtml+xml; charset=UTF-8"/> <script type="text/javascript"> <![CDATA[ function test() { var newsvg = document.getElementById("svg-wrapper"); var svgstr = '<svg:svg height="300" width="700" id="svg-container"><svg:circle cx="150px" cy="100px" r="30px" /></svg:svg>'; newsvg.innerHTML = svgstr; } ]]> </script> <title>SVG DOM</title> </head> <body> <div id="svg-wrapper"></div> <input type="button" onclick="javascript:test();" value="generate svg"/><br/> </body> </html> 

If you want to add a circle to an existing embedded SVG, you need to add it using the DOM methods (and first analyze your string first to extract the required attribute values).

+2
source

I recently looked for something similar to this, but I needed to update part of the existing SVG, so using innerHTML was not an option for me. I ended up watching Canvg pull it out and come up with the following:

 var $contentToReplace = $('svg .some-class'); $contentToReplace.empty(); var content = new DOMParser().parseFromString(newContent, 'text/xml'); // content.children is an HTMLCollection, so using Array.prototype.slice to make a copy. if you // don't make a copy, items will be removed from content.children each time appendChild is called, // which will mess up the loop iteration var children = Array.prototype.slice.call(content.children); for (var i = 0; i < children.length; i++) { $contentToReplace.get(0).appendChild(children[i]); } 

You can check how they did it in Canvg - just find the parseXml method.

You can also pass the parseFromString method to another MIME method. The browser support for them changes a little, although, for example, the MIME type "image / svg + xml" is not supported in IE9 or earlier.

Changing the MIME type simply changes the type of document you are returning. Using 'text / xml' returns an XMLDocument, which works fine in this case.

+1
source

Source: https://habr.com/ru/post/1312842/


All Articles