获得动画线的计算值

Get calculated values of animated line

本文关键字:计算 动画      更新时间:2023-09-26

下面是我的代码:

<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不起作用。

有办法得到这些值吗?

您不是在动画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