首页 > 解决方案 > d3.js:渐变填充是轮廓,如何使它变得立体?

问题描述

我有一个使用 d3.js 的简单条形图,在两个矩形对象上具有线性渐变。渐变在那里,但渐变显示为轮廓(矩形顶部和底部的两条细线)。我想要用渐变填充,而不是轮廓。经过大量研究,我仍然没有答案。

这是 d3 javascript:

var dataArray = [23, 13];
var names = [ "Category1", "Category2" ];
var widths = [ "50", "700" ];

var svg = d3.select("svg.d3svg")
  .attr("height", "20%")
  .attr("width", "100%")

var bar = svg.selectAll("g")
  .data(dataArray)
  .enter().append("g")

var gradient = svg
    .append("linearGradient")
    .attr("y1", "0%")
    .attr("y2", "100%")
    .attr("x1", "0%")
    .attr("x2", "100%")
    .attr("id", "gradient")
    .attr("gradientUnits", "userSpaceOnUse")

gradient
    .append("stop")
    .attr('class', 'start')
    .attr("offset", "0%")
    .attr("stop-color", "red")
    .attr("stop-opacity", 1);

gradient
    .append("stop")
    .attr('class', 'end')
    .attr("offset", "100%")
    .attr("stop-color", "green")
    .attr("stop-opacity", 1);

var rect = bar.append('rect')
  .attr("height", "7")
  .attr("width", function(d, i) { return widths[i] })
  .attr("y", function(d, i) { return (i * 40) + 30 })
  .attr("x", "0")
  .attr("stroke", "url(#gradient)")

var text = bar.append('text')
  .attr("class", "text-svg")
  .text (function(d, i) { return names[i] })
  .attr("x", "0")
  .attr("y", function(d, i) { return (i * 40) + 50 });

var text = bar.append('text')
  .attr("class", "text-svg-caption")
  .text ("Text for this goes here")
  .attr("x", "135")
  .attr("y", "120");

所以我的问题是如何在具有线性渐变的矩形中获得实心填充?

谢谢你的帮助。

标签: javascriptd3.js

解决方案


推荐阅读