当前位置: 代码迷 >> JavaScript >> 具有d3.js和angular的clipPath无法正常工作
  详细解决方案

具有d3.js和angular的clipPath无法正常工作

热度:39   发布时间:2023-06-13 12:16:23.0

我在AngularJS项目中嵌入了一个用d3.js构建的图形,当我放大(使用d3.behavior.zoom)时,我的线条无法保持在图表区域内。 我的标题中没有基本标签。 我的代码的相关部分如下所示:

   this.svg = d3.select(elem).append("svg")
      .attr('class', 'plot')
      .attr('width', this.width + this.margin.left + this.margin.right)
      .attr('height', this.height + this.margin.top + this.margin.bottom)
      .call(responsivefy);

   this.svg.append('defs').append('svg:clipPath')
      .attr('id', 'clip')
   .append('svg:rect')
     .attr('width', this.width)
     .attr('height', this.height)
     .attr('x', this.margin.left)
     .attr('y', this.margin.top);

   this.svg = this.svg.append('g')
     .attr('transform', 'translate(' + this.margin.left + ',' + this.margin.top + ')');

   this.curves_layer = this.svg.append('g');
   var paths = this.curves_layer.selectAll('.line').data(data.series);
   paths.transition()
     .attr('d', function(d) { return line(d.values); }).attr('clip-path', 'url(#clip)')
     .attr('stroke', function(d) { return that.color(d.name)});
   paths.enter().append('path').attr('class', 'line')
     .attr('d', function(d) { return line(d.values); }).attr('clip-path', 'url(#clip)')
     .attr('stroke', function(d) { return that.color(d.name)});
   paths.exit().remove();

我尝试将clip-path属性应用于this.curves_layer组,我尝试放置一个绝对URL而不只是#clip。 没用。 当我放大时,路径溢出图表区域。

相关的角度指令如下所示:

   plots.directive('plot', ['$timeout', '$compile',
   function($timeout, $compile) {
      return {
         restrict: 'E',
         scope: {
            chart: '=',
            data : '='
         },
         link: function(scope, elem, attrs) {
            scope.$watch('chart', function(newVal, oldVal) {
               if (!newVal) return;

               // Clear the directive
               elem.children().remove()
               scope.plot = null;
            });

            scope.$watch('data', function(newVal, oldVal) {
               if (!newVal) return;
               if (!scope.plot) {
                  scope.plot = new Plot(scope.data, elem[0]);
               } else {
                  scope.plot.update(scope.data);
               }

               $compile(elem)(scope);

            }, true);
         }
      };
   }]);

我已经能够通过使用svg标记来解决我的问题,删除了clipPath方法。 代替:

this.curves_layer = this.svg.append('g');

我用了:

this.curves_layer = this.svg.append('svg')
   .attr('height', this.height)
   .attr('width', this.width);

我不知道有可能嵌套多个svg标签。 显然是这样,给定svg之外的所有内容都会被裁剪。