【问题标题】:SVG manipulate gradiant fill colorSVG 操作渐变填充颜色
【发布时间】:2015-12-21 11:21:55
【问题描述】:

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

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

我所做的是尝试在 SVG 开始之前在“linearGradiant”标签中插入“stop”标签 绘制矩形。但不知何故,我的代码不起作用。

我可以看到在我运行我的代码后绘制了矩形,但是 矩形只是没有被渲染。如果我将填充从“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>

【问题讨论】:

  • 以防万一,我想要的效果是一个填充了 2 种不同颜色的矩形。顶部到 33% 将是天蓝色,33% 到 100% 将是黄色

标签: javascript angularjs d3.js svg angularjs-directive


【解决方案1】:

您应该在 &lt;stop&gt; 元素上附加 d3,而不是角度。我很确定 Angular 的 $compile() 将创建位于 HTML/default 命名空间中的 stop 元素。但是,它们需要位于 SVG 命名空间中。

【讨论】:

    猜你喜欢
    • 2020-12-12
    • 2014-01-31
    • 2021-12-05
    • 2017-10-29
    • 2017-02-06
    • 2020-10-07
    • 2012-07-31
    • 1970-01-01
    • 2016-09-16
    相关资源
    最近更新 更多