【发布时间】: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