angularjs - 更改值时为SVG路径设置动画

标签 angularjs svg angularjs-directive

我正在尝试使用SVG和angular指令创建一个图形来更改动态零件。现在,我已经做到了:

http://plnkr.co/edit/TcbK7kyzM3tapDISxndh?p=preview

app.directive('pieChart', function($document) {
    return {
        restrict: "E",
        template: '<svg width="500" height="500">' +
          '<path d="M100,200 a150,150 0 1,0 150,-150" stroke="black" stroke-width="10" fill="none"></path>' +
        '</svg>',
        scope: {
          value: '='
        },
        link: function(scope, elem, attr) {
        }
    }
});


我希望图形的值为100%时,和-假设值为-45%时,看起来像这样,我希望看到这条线,但距顶部中心的长度只有其45%。我可能必须重新计算路径的路径值,但是我想问一下,当我用JS更改路径以使其在更改大小时进行动画处理时,是否可能?

在此先感谢您,或者如果您知道有关此方面的很好的教程,请链接至我。

编辑:我将指令更改为一个简单的条形图,但这仅是举例,我知道可以不用SVG来完成,因为您可以使用divs来使它,但我希望此后的图表更加复杂。

这是一个jsfiddle http://jsfiddle.net/fg9e7eo4/1/

在我的示例中,图表一直保持动画状态,我只想对其进行动画处理,然后再保持该状态。

顺便说一下,这是我正在尝试使其生效的指令:

testApp.directive('pieChart', function() {
  var html = 
    '<svg width="510" height="20" style="background: #fff">' +
      '<path d="{{path}}" stroke="red" stroke-width="10" fill="none">' +
        '<animate dur="1s" repeatCount="indefinite" attributeName="d" values="{{path2}}"/>' +
      '</path>' +
    '</svg>';

  return {
    restrict: 'E',
    template: html,
    scope: {
      'value': '='
    },

    link: function(scope, elem, attrs) {

      scope.$watch('value', function(newValue, oldValue) {
        scope.path = 'M 5 10, L ' + (newValue * 5) + ' 10';
        scope.path2 = 'M 5 10, L ' + (oldValue * 5) + ' 10; M 5 10, L ' + (newValue * 5) + ' 10';
        elem.children().children().beginElement();
      });

    }
  };
});

最佳答案

如果要使用条形图,为什么不使用rect而不是path
IMO,rectpath更具描述性。

这是我使用rect设置动画的示例。

http://plnkr.co/edit/2hEzBqIVgh0rgE3D0Pd4?p=preview

对于AngularJS,只需设置widthto属性。

<rect x="10" y="10" height="110" width="500"
     style="stroke:#ff0000; fill: #0000ff">
    <animate
        attributeName="width"
        begin="0s"
        dur="2s"
        from="0"
        to="500"
    />
</rect>


我认为,这个答案也很有帮助。
SMIL animation on SVG ng-repeat'ed element only occurs on page load

关于angularjs - 更改值时为SVG路径设置动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27279225/

相关文章:

JavaScript - 在函数内连接 2 个参数不起作用

javascript - 无法将变量或动态数据分配给 AngularJS 中的融合图表

javascript - 用JS替换html中一行的具体内容

javascript - 如何使用固定元素使 SVG 响应式?

javascript - 与 Angular Directive(指令) Controller 的两种方式数据绑定(bind)

javascript - AngularJS : Compile directives inside HTML returned by an API

javascript - AngularJs 预渲染

css - 添加 ng-app 指令值时,html css 不起作用

html - Safari 上 SVG foreignObject 中 <video> 元素的错误位置

javascript - AngularJS:指令找不到注入(inject)的依赖项