获取动画线的计算值

时间:2011-11-08 11:38:32

标签: javascript svg

这是我的代码:

<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>

我试图在动画过程中获得线坐标的计算值。但看起来animVal.value不起作用。

有没有办法获得这些价值?

1 个答案:

答案 0 :(得分:3)

您没有为点x1x2制作动画,而是为transform设置动画。如果要在另一个坐标系中查看这些点的值,则需要将它们从线的坐标系转换为另一个坐标系。例如:

<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>

在此处查看此行动:http://phrogz.net/SVG/animated_point_values.svg