2015-09-24 151 views
0

我想在一个简单的svg矩形中编程操纵渐变填充颜色。SVG操作渐变填充颜色

有2种解决方案。我不喜欢绘制多个反义词并将它们连接在一起以获得一个大反应。所以我正在尝试这种渐变颜色方法。

我所做的是试图在“linearGradiant”标记中插入“stop”标记,然后SVG开始绘制矩形 。但不知何故,我的代码不工作。

我可以看到矩形是在我运行我的代码之后绘制的,但是 矩形只是没有呈现。如果我将填充从“url(#c1)”更改为“blue”,我可以看到矩形会呈现蓝色。

代码正在使用AngularJS指令。

'use strict' 

angular.module('StanfordClinicalGenomics').directive('chromosomeFillChart', ['$compile', '$location',function($compile,$location) { 

return { 

    restrict: 'E', 
    templateUrl: "app/directives/chromosome_fill/chromosome_fill.html", 
    scope: { 
     data: "=data", 
     cid: "=cid", 
     vid: "=vid", 
    }, 
    controller: function($scope, $element, $attrs, $compile, $http, $route, $rootScope, $timeout) { 

     var data = $scope.data; 

     if ($scope.cid){ 
      var chart = d3.select('chromosome-fill-chart[cid='+"'"+$scope.cid+"'"+'] svg.withFill') //this is just a selector 
      .attr("width", 30) 
      .attr("height", 100); 


      $timeout(function(){ 
       angular.element("#c"+$scope.cid).append($compile('<stop offset="33%" stop-color="skyblue" />')($scope)); 

       angular.element("#c"+$scope.cid).append($compile('<stop offset="33%" stop-color="#FF6" />')($scope)); 
       $scope.$apply(); 
       var bar = chart.append("g") 
       .append("rect") 
       .attr("width", 30) 
       .attr("fill", "url(#c"+$scope.cid+")") 
       .attr("height",data[0]); 


      });  
     } 
    } 
} 

}]);

下面是HTML:

<svg class="withFill"> 
<defs> 
    <linearGradient id="c{{cid}}" x1="0%" y1="0%" x2="0%" y2="100%"></linearGradient> 
</defs> 
</svg> 

下面是代码在我的Chrome浏览器:

<chromosome-fill-chart data="[100,20,76]" cid="1" class="ng-isolate-scope"> 
<svg class="withFill" width="30" height="100"> 

    <defs> 
     <linearGradient id="c1" x1="0%" y1="0%" x2="0%" y2="100%"> 
      <stop offset="33%" stop-color="skyblue" class="ng-scope"></stop> 
      <stop offset="33%" stop-color="#FF6" class="ng-scope"></stop> 
     </linearGradient> 
    </defs> 


<g><rect width="30" fill="url(#c1)" height="100"></rect></g> 
</svg> 
</chromosome-fill-chart> 
+0

为了以防万一,我的预期效果将是一个填充2种不同颜色的矩形。高达33%将是天蓝色,33%至100%将是黄色 – user3781258

回答

1

你应该添加您的<stop>元素与D3,没有棱角。我很确定Angular的$compile()将创建stop元素,它们位于HTML /默认名称空间中。但是他们需要在SVG名称空间中。

+0

它的工作原理。非常感谢 – user3781258