Dynamically create SVG with javascript
Following is an example of dynamically created SVG pattern with javascript and DOM. The name space part is tricky and can be frustrating for people not familiar with it. The hard parts are high lighted in red.
=============================
<?xml version="1.0" ?> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:svg="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" lang="en-US"> <head> <meta http-equiv="Content-Type" content="application/xhtml+xml;charset=utf-8"/> <title>SVG</title> <style type="text/css"> #drawingPad{ width:100px; height:100px; overflow:hidden; border:1px solid black; position:absolute } </style> <script type="text/javascript"> <![CDATA[ //________________________________ var xhtmlNS = "http://www.w3.org/1999/xhtml"; var svgNS = "http://www.w3.org/2000/svg"; var xlinkNS ="http://www.w3.org/1999/xlink"; function makeCircle(x, y, r){ var vCircle = document.createElementNS(svgNS, "svg:circle") vCircle.setAttributeNS( null, "cx", new String( x ) + "px" ); vCircle.setAttributeNS( null, "cy", new String( y ) + "px" ); vCircle.setAttributeNS( null, "r", new String( r ) +"px"); vCircle.setAttributeNS( null, "style", "fill:blue"); return vCircle; } function makeLine(x1, y1, x2, y2){ var vLine = document.createElementNS(svgNS, "svg:line") vLine.setAttributeNS( null, "x1", new String( x1 ) + "px" ); vLine.setAttributeNS( null, "y1", new String( y1 ) + "px" ); vLine.setAttributeNS( null, "x2", new String( x2 ) + "px" ); vLine.setAttributeNS( null, "y2", new String( y2 ) + "px" ); vLine.setAttributeNS( null, "style", "stroke-width:2;stroke:red"); return vLine; } function drawPattern(){ var vPad = document.getElementById( "drawingPad" ); var vSVGElem = document.createElementNS(svgNS, "svg:svg"); var i; var r = 20; var vAX = new Array(); var vAY = new Array(); for( i = 0 ; i < 7 ; i ++ ){ var vAngle = Math.PI * 4 / 7 * i var vX = Math.cos(vAngle) * r + 50 var vY = Math.sin( vAngle ) * r + 50 var vC = makeCircle(vX, vY, 4); vSVGElem.appendChild( vC); vAX[ i ] = vX vAY[ i ] = vY if( i > 0 ){ var vLine = makeLine(vX, vY, vAX[ i - 1 ], vAY[ i - 1 ]); vSVGElem.appendChild( vLine ); } } vPad.appendChild(vSVGElem) } ]]>--> </script> </head> <body> <form> <input type="button" onclick="drawPattern(); return false;" value="Click"/> </form> <div id="drawingPad"> </div> </body> </html>=============================
Labels: javascript, svg
0 Comments:
Post a Comment
<< Home