ya.teck
ya.teck

Reputation: 2336

Get calculated values of animated line

Here is my code:

<svg  id="canvas" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
  <line id="line" x1="100" y1="100" x2="150" y2="150" style="stroke:rgb(255,0,0);">
   <animateTransform
      attributeName="transform"
      begin="0s"
      dur="15s"
      type="rotate"
      from="0 100 100"
      to="360 100 100"
      repeatCount="indefinite" 
    />
  </line>
  <script>
  setInterval(function(){
  var line = document.getElementById('line')
  // This line returns "100 100"
  console.log('point_1: ',line.x1.animVal.value, line.y1.animVal.value)
  // This line returns "150 150"
  console.log('point_2: ',line.x2.animVal.value, line.y2.animVal.value)
  }, 500)
  </script>
</svg>

I am trying to get calculated values of line coordinates during animation process. But it looks like animVal.value doesn't work.

Is there any way to get these values?

Upvotes: 3

Views: 401

Answers (1)

Phrogz
Phrogz

Reputation: 303234

You're not animating the points x1 and x2, you're animating the transform. If you want to see the values of these points in another coordinate system, you need to transform them from the line's coordinate system into that other space. For example:

<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 200 200">
  <style type="text/css">
    circle { opacity:0.5 } #c1 { fill:green } #c2 { fill:blue }
  </style>
  <line id="line" x1="100" y1="100" x2="150" y2="150" stroke="red">
   <animateTransform
      attributeName="transform"
      begin="0s"       dur="15s"
      type="rotate"    repeatCount="indefinite" 
      from="0 100 100" to="360 100 100" />
  </line>
  <circle id="c1" r="5" /><circle id="c2" r="5" />
  <text y="30">Hello</text>
  <script type="text/javascript">
  var svg  = document.documentElement;
  var line = document.getElementById('line')
  var pt1 = svg.createSVGPoint(), pt2 = svg.createSVGPoint();
  pt1.x = line.x1.baseVal.value; pt1.y = line.y1.baseVal.value;
  pt2.x = line.x2.baseVal.value; pt2.y = line.y2.baseVal.value;
  var c1 = document.getElementById('c1');
  var c2 = document.getElementById('c2');
  var t  = document.getElementsByTagName('text')[0].childNodes[0];
  setInterval(function(){
    var lineToSVG = line.getTransformToElement(svg);
    var p1 = pt1.matrixTransform( lineToSVG );
    var p2 = pt2.matrixTransform( lineToSVG );
    c1.cx.baseVal.value = p1.x; c1.cy.baseVal.value = p1.y;
    c2.cx.baseVal.value = p2.x; c2.cy.baseVal.value = p2.y;
    var angle = Math.round(Math.atan2(p2.y-p1.y,p2.x-p1.x)*180/Math.PI);
    t.nodeValue = "Angle:" + angle +"°";
  }, 200);
  </script>
</svg>

See it in action here: http://phrogz.net/SVG/animated_point_values.svg

Upvotes: 3

Related Questions