Javascript create use element

I am trying to create a “use” node using javascript, but the result cannot be seen on the screen, does anyone have an idea? By the way, creating some other type works great, for example, creating an ellipse.

Here are the codes.

<!DOCTYPE html> <html> <head> <meta http-equiv="Content-type" content="text/html;charset=UTF-8" /> <script type="text/javascript" src="http://code.jquery.com/jquery-1.7.2.min.js"> </script> <script type="text/javascript"> //this can work function onEllipse(){ var ellipse = document.createElementNS("http://www.w3.org/2000/svg", "ellipse"); ellipse.setAttribute("cx", "20"); ellipse.setAttribute("cy", "40"); ellipse.setAttribute("rx", "20"); ellipse.setAttribute("ry", "10"); ellipse.setAttributeNS(null,'style','visibility:visible;fill:green'); svg.appendChild(ellipse); } //this **WON"T** work, the referenced node "#circle1" is alredy in the "defs" function onUse(){ var xmlns = "http://www.w3.org/2000/svg"; var svgns = 'http://www.w3.org/2000/xlink/namespace/'; var Node = document.createElementNS(xmlns,'use'); Node.setAttributeNS(null,'id','abcd'); Node.setAttributeNS(null,'x','200'); Node.setAttributeNS(null,'y','200'); Node.setAttributeNS(null,'style','visibility:visible;fill:green'); Node.setAttributeNS(svgns,'xlink:href','#circle1'); svg.appendChild(Node); } var svg; $(document).ready(function(){ svg = document.getElementsByTagName('svg')[0]; }); </script> </head> <body> <div id="left-toolbar" style="float:left;border:1px solid #DDDDDD;overflow:auto"> <input type='button' onclick='onEllipse()' value='ellipse' /><br /> <input type='button' onclick='onUse()' value='use' /><br /> </div> <div id="workarea" style="float:left;border:1px solid #DDDDDD;margin:0px 20px 0px 20px;overflow:auto"> <svg width="1280px" height="720px" viewBox="0 0 1280 720" xmlns="http://www.w3.org/2000/svg"> <defs> <circle id="circle1" cx="35" cy="20" r="20" style="stroke: black; fill: none;" /> </defs> <!--use x="100" y="100" xlink:href = "#circle1"/--> </svg> </div> </body> </html> 
+4
source share
2 answers

Xlink namespace is http://www.w3.org/1999/xlink , so you want

 var svgns = 'http://www.w3.org/1999/xlink'; 

Although calling the xlink svgns namespace may seem like a source of confusion to me.

+4
source

Using:

 var xlink = 'http://www.w3.org/1999/xlink'; Node.setAttributeNS(xlink,'href','#circle1'); 

instead:

 var svgns = 'http://www.w3.org/2000/xlink/namespace/'; Node.setAttributeNS(svgns,'xlink:href','#circle1'); 
+1
source

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


All Articles