Question

I have an embedded SVG in an HTML document. An (SVG) circle is animated using <animate>. I was trying to find a way to put some kind of event listener on that circle only when it moves horizontally.

Upon being moved (horizontally), I'd like to find the x-coordinates of the circle shape and set a third (outside) rect shape width to the relative position of the circle. This third rect would be like a progress bar tracking the horizontal progress of the circle.

Does the SVG circle (by the way, the circle is inside an SVG g-group) being moved by trigger some kind of event I can set a listener so that then I can change the width attribute of the sort of progress bar?

I have thought that if either the <animate> or the element moved/changed triggers some kind of event I could try to catch it and then change the width on the bar.

I have found that it is not much good use an "independent" animate on the rect as the pace of growth is very different when the circle moves upwards. I am not using the canvas element because I am trying to keep the scalability and the shapes semantics. (I would rather prefer a javascript solution but I would be grateful for other approaches.)

EDIT after answer: The anser have ben very much to the piint and (I think) helpful. I am very new to SVG and I may have misinterpreted something. Fot that reason I am including code.

I have tried to implement your recommendations and I seem to have been unsuccessful. .cx.animVal.value applied to the circle does not seem to get me what I need. I will include a chopped version of my code which should move a ball along a path which itself is being moved horizontally; two rects (inBar and outBar) should be tracking the horizontal displacement growing horizontally more or less at the same rate as the ball. In order to make sure setInterval works and the position is correctly gathered, a line has been added to list oBall..animVal and oball..baseVal. In FF 21.0, there is no change for animVal along the displacement. Have I understood your suggestions correctly? here follow the code (including headers etc. as I am a noob in SVG in particular):

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en" dir="ltr">
    <head><title>Motion</title>
    <script>function beginAnim(anim,sPos){anim.beginElement();}</script>
    </head>
    <body>
    <div id="here">
    <button onclick="beginAnim(document.getElementById('anim'),'out');">START</button>
    </div>
    <div style="height:350px;">
    <svg width="100%" height="100%" version="1.1" xmlns="http://www.w3.org/2000/svg">
    <script type="text/ecmascript">
    <![CDATA[
      function trckngBars(){
        oDiv=document.getElementById('here');
        var oBall=document.getElementById('ball');
        var oBar=[document.getElementById('inBar'),document.getElementById('outBar')];
        idTimer=self.setInterval(function(){updtBars(oBall,oBar);},100);
      }
      function updtBars(oBall,oBar){
        var xCoor=String(oBall.cx.animVal.value);
        oDiv.innerHTML+='==>'+oBall.cx.animVal.value+'..'+oBall.cx.baseVal.value;
        oBar[0].setAttribute("width",xCoor);
        oBar[1].setAttribute("width",xCoor);
      }
    // ]]>
    </script>
    <defs>
    <path id="throw" d="M0,0 q 80,-55 200,20" style="fill: none; stroke: blue;" />
    </defs>
    <g>
      <g>
        <rect x="2" y="50" width="400" height="110" style="fill: yellow; stroke: black;"></rect>
      </g>
      <g>
        <!-- show the path along which the circle will move -->
        <use id="throw_path" visibility="hidden" xlink:href="#throw" x="50" y="130" />
        <circle id="ball" cx="50" cy="130" r="10" style="fill: red; stroke: black;">
          <animateMotion id="ball_anim" begin="anim.begin+1s" dur="6s" fill="freeze" onbegin="trckngBars();" onend="window.clearInterval(idTimer);">
            <mpath xlink:href="#throw" />
          </animateMotion>
        </circle>
        <rect id="inBar" x="50" y="205" width="20" height="30" style="fill: purple;stroke-linecap: butt;">
    <!-- <animate attributeType="XML" attributeName="width" from="0" to="200" begin="ball_anim.begin" dur="6s" fill="freeze" /> -->
</rect>
      </g>
      <animateTransform id="anim" attributeType="XML" attributeName="transform" type="translate" from="0" to="200" begin="indefinite" dur="10s" fill="freeze" />
    </g>
    <rect id="outBar" x="50" y="235" width="10" height="30" style="fill: orange;stroke-linecap: butt;">
    <!-- <animate attributeType="XML" attributeName="width" from="0" to="400" begin="anim.begin+1s" dur="10s" fill="freeze" /> -->
</rect>
    </svg> 
    </div>
    </body>
    </html>

If the code is run, it seems that animVal for the moving #ball remains at the same x-coordinat (50) while clearly it is moving.

Was it helpful?

Solution

An event is fired when animations begin, end or repeat but not (as you want) whenever there is a change of animation value.

As animations are deterministic though you can just start the rect shape animation so many seconds after the circle animation starts.

var cx = myCircle.cx.animVal.value;

will give you the animated value if you need it, provided that's the attribute you're animating.

You're using animateMotion rather than animating the cx and cy attributes on their own though. I'm think the only way to get the circle position post that transform is to call getBBox.

OTHER TIPS

@Robert Thank you very much for your help. Your answer has been a good plunge into SVG and SMIL (and let me add cold). I have not been able to use getBBox, but inspecting the specification on paths ([link] http://www.w3.org/TR/SVG11/paths.html) and animateMotion (same site), it apears that can be achieved as SMIL animations are deterministic as suggested in your answer.

An animation has very few event triggers and by design seem as much concerned with the base state of the animation target as it is with the current position (theseem to be referred as "base values" and "presentation values"). (All the following works in javascript run by FF 21.) We can poll the current time of the animation applying getCurrentTime on the animateMotion object. I am assuming that the animation does it at constant velocity, so with that, we determine how much the object has moved along the path and obtain the length traversed (as we can get the total length of the whole path with method getTotalLength).

Then knowing the length, we can determine the current position on the path (using method getPointAtLength). Note, that the values returned, both time and position are relative to the container object, and thus they are scalable and/or require transformation).

For a (simple) working example, the javascript code in the Question sample code can be replaced by the following. It appears to work with the very few tests I have made:

  function trckngBars(){
    /* Upon beginning an animation (onbegin event), the required objects are gathered
    and an interval is set */
    var oBall=[document.getElementById('throw'),document.getElementById('ball_anim')];
    var oBar=document.getElementById('inBar');
    /* idTimer is set as a global variable so that it can be accessed from anywhere
    to clear the interval*/
    idTimer=self.setInterval(function(){updtBars(oBall,oBar);},50);
  }
  function updtBars(oBall,oBar){
    /* This function, whose purpose is only to illustrate path method getPointLength 
    and animateMotion method getCurentTime, is quick and dirty. Note that oBall[0] is
    the path and oBall[1] is the animate(Motion) */
    //Calculates the amount of time passed as a ratio to the total time of the animation
    var t_ratio=((oBall[1].getCurrentTime()-oBall[1].getStartTime())/oBall[1].getSimpleDuration());
    // As mentioned, it assumes that animateMotion performs uniform motion along path
    var l=oBall[0].getTotalLenth()*t_ratio;
    // Gets (relative referred as user in documentation) horizontal coordinate
    var xCoor=oBall[0].getPointAtLength(l).x;
    oBar.setAttribute("width",xCoor);
  }
  function endTAnim(){
    /* This function can be triggered _onend_ of an animation to clear the interval
    and leave bars with the exact last dimensions */
    window.clearInterval(idTimer);
    var oBar=[document.getElementById('inBar'),document.getElementById('outBar')];
    oBar[0].setAttribute("width",200); //hardcoded for convenience
  }

Thus the simplest method I have been able to find requires the animation object (to obtain the time) and the path object (to "predict" the position) and it does not involve the actual element being moved by the animation. (It is somewhat simplifiedfrom the initial question to avoid discussing different coordinate systems when composed animations are used - this might be better discussed ia a stand-alone way.)

Though I have not noticed any lag (as the actual SVG is not much more complicated), I would be interested in knowing computationally cheaper methods as I was considering using this approach to find and draw a distance segment between two SMIL animated objects.

Of course all this relies on the assumption of a uniform movement aong the path, if that were not so and in larger images one might notice and offset I would also be grateful for any pointers on that (short of better do the animation directly in javascript/programming language and so you have total control). Thank you for all te edits you did avoiding getting into a quagmire - the only thing I knew about SVG three days ago is that it was XML.

A while ago I ran into the same problem you are describing. I wanted to be able to stop animations halfway, based on events triggered by the user and keep elements at their reached position. Unable to do so with SMIL I decided to forge my own animation system for svg.js, a small javascript library I have been working on:

http://documentup.com/wout/svg.js#animating-elements

It might be useful for what you are trying to achieve.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top