× {{alert.msg}} Never ask again
Get notified about new tutorials RECEIVE NEW TUTORIALS

Manipulate elements in SVG file (object) by JavaScript or JQuery

Drew Taylor
May 08, 2015
<p>Normally I use D3.js library when I want to create or manipulate SVG graphics by javascript alone. <a href="http://d3js.org/" rel="nofollow">http://d3js.org/</a></p> <p>Unlike libs like Raphaeljs, which polyfills, D3 provides a javascript API for direct manipulation of SVG elements within the browser in real time.</p> <blockquote> <p><strong>D3 is Not a SVG Polyfill:</strong> Unlike Raphaël, which provides polyfill for SVG on browsers that do not support SVG. D3 manipulates SVG directly, without any abstraction layer. Your browser needs to support SVG for D3 to work properly. (<a href="http://ruoyusun.com/2014/05/26/what-d3js-is-not.html" rel="nofollow">source</a>)</p> </blockquote> <p>For example, here's a demo I made from a D3 tutorial that constructs and manipulates SVG elements to create a live javascript / svg driven clock using the Javascript native <code>new Date()</code> function: <a href="http://jsfiddle.net/2jogwx6x/1/" rel="nofollow">http://jsfiddle.net/2jogwx6x/1/</a></p> <p>The D3.js strategy will likely work for your purposes and the elem selection method is similar to jQuery's CSS selection method but working directly with dom nodes, but for it to work you would need to directly embed your SVG data into the DOM like:</p> <pre><code>&lt;!-- simple rectangle - replace this with your real svg data --&gt; &lt;svg width="400" height="110"&gt; &lt;rect width="300" height="100" style="fill:rgb(0,0,255);stroke-width:3;stroke:rgb(0,0,0)"&gt; &lt;/svg&gt; </code></pre> <p>Instead of using <code>&lt;object id="testSVG" data="image_library/grandstaff_drawing_only.svg" type="image/svg+xml" height=100% width=100%"&gt;</code></p> <p>To manipulate SVG data in the DOM on the fly it has to be a part of the DOM and not opening / writing to / closing an external file.</p> <p>This tip was originally posted on <a href="http://stackoverflow.com/questions/30005163/Manipulate%20elements%20in%20SVG%20file%20(object)%20by%20JavaScript%20or%20JQuery/30005626">Stack Overflow</a>.</p>

Get New Tutorials Delivered to Your Inbox

New tutorials will be sent to your Inbox once a week.

comments powered by Disqus