38

I've been searching for ways to run scripts for my SVG. But all the things I got don't match up! And it doesn't contain enough information why each set of codes were used. For example, one used event.target, another had event.getTarget(), and another had event.target.firstchild.data.

<svg xmlns="http://www.w3.org/2000/svg" version="1.1">
  <path d="M150 0 L75 200 L225 200 Z" />
</svg>

This is an example of a path svg, right? What I need is to get those coordinates, probably put it in a variable, and use it as coordinates for another svg. So how can I do that? Another thing is how can I change those coordinates by entering numbers in an interface?

Laurel
  • 5,965
  • 14
  • 31
  • 57
Lendl Leyba
  • 2,287
  • 3
  • 34
  • 49
  • You need to provide much more information on your question. What specifically is your problem? What are you trying to accomplish, what is your code, what is the results you are seeing? Are you just looking for any SVG template that shows scripting working? Are you embedding SVG in XHTML, or is this a standalone SVG file? etc. – Phrogz Nov 08 '11 at 17:47

2 Answers2

114

It sounds like you may have four questions:

  1. How do I embed script inside an SVG file?
  2. How do I run script inside an SVG file?
  3. How do I access data for a <path> element from script?
  4. How can I manipulate data for a <path> element from script?

Let's tackle them one at a time:


How do I embed script inside an SVG file?

As described in the SVG specification you can place a <script> element in your document to contain JavaScript code. According to the latest SVG specifications, you do not need to specify a type attribute for your script. It will default to type="application/ecmascript".

  • Other common mime types include "text/javascript", "text/ecmascript" (specified in SVG 1.1), "application/javascript", and "application/x-javascript". I do not have detailed information on browser support for all of these, or for omitting the type attribute altogether. I have always had good success with text/javascript.

As with HTML, you may either put the script code directly in the document, or you may reference an external file. When doing the latter, you must use an href attribute (not src) for the URI, with the attribute in the xlink namespace.

<svg version="1.1" baseProfile="full" xmlns="http://www.w3.org/2000/svg"
     xmlns:xlink="http://www.w3.org/1999/xlink">
  <script xlink:href="/js/mycode.js" />
  <script><![CDATA[
    // Wrap the script in CDATA since SVG is XML and you want to be able to write
    // for (var i=0; i<10; ++i )
    // instead of having to write
    // for (var i=0; i&lt;10; ++i )
  ]]></script>
</svg>

How do I run script inside an SVG file?

As with HTML, code included in your SVG document will be run as soon as it is encountered. If you place your <script> element above the rest of your document (as you might when putting <script> in the <head> of an HTML document) then none of your document elements will be available when your code is running.

The simplest way to avoid this is to place your <script> elements at the bottom of your document:

<svg version="1.1" baseProfile="full" xmlns="http://www.w3.org/2000/svg"
     xmlns:xlink="http://www.w3.org/1999/xlink">
  <!-- all SVG content here, above the script -->
  <script><![CDATA[
    // Now I can access the full DOM of my document
  ]]></script>
</svg>

Alternatively, you can create a callback function at the top of your document that is only invoked when the rest of the document is ready:

<svg version="1.1" baseProfile="full" xmlns="http://www.w3.org/2000/svg">
  <title>SVG Coordinates for Embedded XHTML Elements</title>
  <script>document.documentElement.addEventListener('load',function(){
    // This code runs once the 'onload' event fires on the root SVG element
    console.log( document.getElementById('foo') );
  },false)</script>
  <path id="foo" d="M0 0" />
</svg>

How do I access data for a <path> element from script?

There are two ways to access most information about elements in SVG: you can either access the attribute as a string through the standard DOM Level 1 Core method getAttribute(), or you can use the SVG DOM objects and methods. Let's look at both:

Accessing path data through getAttribute()

Using getAttribute() returns the same string as you would see when you view source:

<path id="foo" d="M150 0 L75 200 L225 200 Z" />
<script><![CDATA[
  var path = document.getElementById('foo');
  var data = path.getAttribute('d');
  console.log(data);
  //-> "M150 0 L75 200 L225 200 Z"
]]></script>
  • Pros: very simple to call; you don't have to know anything about the SVG DOM
  • Con: since you get back a string you have to parse the attribute yourself; for SVG <path> data, this can be excruciating.

Accessing path data through SVG DOM methods

<path id="foo" d="M150 0 L75 200 L225 200 Z" />
<script><![CDATA[
  var path = document.getElementById('foo');

  // http://www.w3.org/TR/SVG/paths.html#__svg__SVGAnimatedPathData__normalizedPathSegList
  // See also path.pathSegList and path.animatedPathSegList and path.animatedNormalizedPathSegList
  var segments = path.normalizedPathSegList ;

  for (var i=0,len=segments.numberOfItems;i<len;++i){
    var pathSeg = segments.getItem(i);
    // http://www.w3.org/TR/SVG/paths.html#InterfaceSVGPathSeg
    switch(pathSeg.pathSegType){
      case SVGPathSeg.PATHSEG_MOVETO_ABS:
        // http://www.w3.org/TR/SVG/paths.html#InterfaceSVGPathSegMovetoAbs
        console.log("Move to",pathSeg.x,pathSeg.y);
      break;
      case SVGPathSeg.PATHSEG_LINETO_ABS:
        // http://www.w3.org/TR/SVG/paths.html#InterfaceSVGPathSegLinetoAbs
        console.log("Line to",pathSeg.x,pathSeg.y);
      break;
      case SVGPathSeg.PATHSEG_CLOSEPATH:
        // http://www.w3.org/TR/SVG/paths.html#InterfaceSVGPathSegClosePath
        console.log("Close Path");
      break;
    }
  }
]]></script>

The above script produces the following output:

Move to 150 0
Line to 75 200
Line to 225 200
Close Path
  • Pros: path data is parsed for you; you get exact numbers from the API itself; using normalizedPathSegList takes relative commands and makes them absolute for you; if SMIL animation is changing the path data, using the non-animated pathSegList can give you access to the base, non-animated information not available via getAttribute().

  • Cons: Sweet chimpunks a-flame, look at that code! And that doesn't even handle all the possible path segments available.

Because it can be hard to read the W3C specs for SVG DOM, many years ago I created an online tool for browsing what properties and objects exist. You may use it here: http://objjob.phrogz.net/svg/hierarchy


How can I manipulate data for a <path> element from script

Similar to the above, you can either create a new string and use setAttribute() to shove it onto the object, or you can manipulate the SVG DOM.

Manipulating path data using setAttribute()

<path id="foo" d="M150 0 L75 200 L225 200 Z" />
<script><![CDATA[
  var path = document.getElementById('foo');
  path.setAttribute('d','M150,0 L150,100 200,300 Z');
]]></script>

Manipulating path data using SVG DOM

<path id="foo" d="M150,0 L75,200 l150,0 Z" />
<script><![CDATA[
  var path = document.getElementById('foo');
  var segments = path.pathSegList;
  segments.getItem(2).y = -10;
]]></script>

In general, you just have to modify the properties of the various SVGPathSeg subclass instances; the changes are made immediately in the DOM. (With the above example, the original triangle is skewed as the last point is moved up slightly.)

When you need to create new path segments, you need to use methods like var newSegment = myPath.createSVGPathSegArcAbs(100,200,10,10,Math.PI/2,true,false) and then use one of the methods to stick this segment into the list, e.g. segments.appendItem(newSegment).

Phrogz
  • 296,393
  • 112
  • 651
  • 745
  • Thanks thanks. But, does these also take effect on embedded SVG's? – Lendl Leyba Nov 27 '11 at 12:46
  • @LeiLeyba Yes. Here's [a simple example of SVG embedded in XHTML that uses scripting](http://phrogz.net/svg/svg_in_xhtml5.xhtml). – Phrogz Nov 27 '11 at 15:15
  • @LeiLeyba Here's another example that has SVG embedded in XHTML in order to [manipulate a path](http://phrogz.net/svg/constant-length-bezier.xhtml). – Phrogz Nov 27 '11 at 15:22
  • @Phrogz you have to write a book about SVG. On StackO you give enough material to do that. Thanx man. – Alex Nov 28 '11 at 07:18
  • @Phrogz What i meant was an embedded svg like, '' because i made a separate svg file from adobe illustrator, on which i want to use for my page. – Lendl Leyba Nov 29 '11 at 07:42
  • @LeiLeyba Try It And See™ :) You will find that the script included in the embedded file will run for that file, but the host HTML (or SVG) cannot access the DOM of an embedded file. (Also, note that modern browsers support `` equally well as a way of referencing an external SVG image. – Phrogz Nov 29 '11 at 13:40
  • @Phrogz Yeah man, exactly. How about ? or how about it in iframe src? Lol. Sorry, i'm so new at this. I need to access my separate svg's dom inside an html. or should i just code the svg inside the html? but i think i've tried it before and the jquery svgpan i put didn't seem to work. – Lendl Leyba Nov 30 '11 at 03:35
  • @LeiLeyba Holy monkey, enough! Stack Overflow is not a discussion board. Join the chat, or post new questions to the site. An extended back-and-forth in the comments is not appropriate. We are now rather far from the topic of your original question. Post a new one, tag it with SVG, and I (and others) will see it and help. – Phrogz Nov 30 '11 at 03:38
  • @Phrogz Haha. Ok ok. Don't start calling holy creatures now. But you really should write a book about SVG's. thanks man. see you on another question. Lol – Lendl Leyba Nov 30 '11 at 03:45
  • @Phrogz Kindly clarify the below doubt. In http://objjob.phrogz.net/svg/hierarchy, it shows like SVGPathElement inherits from SVGAnimatedPathData. Also the in the http://objjob.phrogz.net/svg/object/101 it says SVGPathElement inherits from SVGAnimatedPathData. But http://www.w3.org/TR/SVG/paths.html#InterfaceSVGPathElement shows SVGPathElement implements from SVGElement,SVGTests,SVGLangSpace,SVGExternalResourcesRequired, SVGStylable,SVGTransformable, SVGAnimatedPathData. Please clarify how to know all the interfaces that a particular interface implements. Other tabs are really helpful thanks. – Rajkamal Subramanian Mar 20 '12 at 07:10
  • @rajkamal Thank you for bringing this to my attention. The flaw has been fixed. _(ObjJob was previously only supporting single inheritance (!); the SVG 1.1 IDL has now been parsed with [correct inheritance](http://objjob.phrogz.net/svg/hierarchy).)_ – Phrogz Mar 20 '12 at 20:50
  • @Phrogz, welcome, but i think its not fixed. for example in the new version, SVGAElement extends only SVGElement (in the hierarchy tree ). but w3 doc says some more things. :-( – Rajkamal Subramanian Mar 22 '12 at 15:55
  • @rajkamal I think you are misreading how the hierarchy tree presents things. Look at [`SVGAElement`](http://objjob.phrogz.net/svg/object/2) and note how many items it inherits from, or search for "SVGAElement" on the hierarchy page. For further discussion, let's continue [over email](http://phrogz.net/contact). – Phrogz Mar 22 '12 at 17:55
  • 2
    Alternative for deprecated SVG pathSegList: http://stackoverflow.com/questions/34352624/alternative-for-deprecated-svg-pathseglist – Alexei Zababurin Jan 15 '16 at 17:00
  • 2
    It's recommended to use new getPathData and setPathData API instead of old pathSegList API. The new API is much more efficient and has better usability. Use [path data polyfill](https://github.com/jarek-foksa/path-data-polyfill.js) to work with new API. – cuixiping May 27 '16 at 03:09
  • Thanks for all this info and for clarifying a few things that are surprisingly poorly documented. – catch22 Feb 06 '18 at 20:59
5

Dynamic Path elements in SVG with Javascript and Css support

var XMAX = 500;
var YMAX = 500;
var _xx=10;
var _reg=100;
var _l=10;
// Create PATH element
for(var x=1;x<20;x++)
{
    var pathEl = document.createElementNS("http://www.w3.org/2000/svg", "path");
    pathEl.setAttribute('d','M'+_l+' 100 Q 100  300 '+_l+' 500' );
    pathEl.style.stroke = 'rgb('+(_reg)+',0,0)';
    pathEl.style.strokeWidth = '5';
    pathEl.style.fill = 'none';

    $(pathEl).mousemove(function(evt){$(this).css({"strokeWidth":"3","stroke":"#ff7200"}).hide(100).show(500).css({"stroke":"#51c000"})});
    
    document.querySelector('svg').appendChild(pathEl);
    _l+=50;
}

Demo in jsfiddle

Laurel
  • 5,965
  • 14
  • 31
  • 57
Godly Mathew
  • 111
  • 2
  • 3
  • 2
    An odd example, but I'll take it. – I. J. Kennedy Oct 24 '15 at 16:48
  • Agree with @Kennedy... this example makes some good points, but it is a bit quirky (what are `XMAX`, `YMAX`, and `_xx` for? Why is the svg element not declared with a bounding box? And so we get a little default 300x150 view showing little almost-linear sections of those cool quadratic curves...) – personal_cloud Oct 07 '17 at 23:33