答案 0 :(得分:3)
您必须将gradientUnits
设置为userSpaceOnUse
。根据文档,userSpaceOnUse:
...表示坐标系中的值,这些值是在引用渐变元素时获取当前用户坐标系所得到的
这是一个没有userSpaceOnUse
的演示,结果不是你想要的:
var svg = d3.select("svg");
var gradient = svg.append("defs")
.append("linearGradient")
.attr("id", "gradient")
.attr("x1", "0%")
.attr("y1", "50%")
.attr("x2", "100%")
.attr("y2", "50%");
gradient.append("stop")
.attr("offset", "0%")
.attr("stop-color", "Black")
.attr("stop-opacity", 1);
gradient.append("stop")
.attr("offset", "100%")
.attr("stop-color", "white")
.attr("stop-opacity", 1);
var g = svg.append("g")
.style("fill", "url(#gradient)");
var rects = g.selectAll("foo")
.data(d3.range(7))
.enter()
.append("rect")
.attr("y", 20)
.attr("x", (d, i) => 20 + 50 * i)
.attr("width", 40)
.attr("height", 40);

<script src="https://d3js.org/d3.v4.min.js"></script>
<svg width="400"></svg>
&#13;
现在有userSpaceOnUse
的演示:
var svg = d3.select("svg");
var gradient = svg.append("defs")
.append("linearGradient")
.attr("id", "gradient")
.attr("x1", "0%")
.attr("y1", "50%")
.attr("x2", "100%")
.attr("y2", "50%")
.attr("gradientUnits","userSpaceOnUse");
gradient.append("stop")
.attr("offset", "0%")
.attr("stop-color", "Black")
.attr("stop-opacity", 1);
gradient.append("stop")
.attr("offset", "100%")
.attr("stop-color", "white")
.attr("stop-opacity", 1);
var g = svg.append("g")
.style("fill", "url(#gradient)");
var rects = g.selectAll("foo")
.data(d3.range(7))
.enter()
.append("rect")
.attr("y", 20)
.attr("x", (d, i) => 20 + 50 * i)
.attr("width", 40)
.attr("height", 40);
&#13;
<script src="https://d3js.org/d3.v4.min.js"></script>
<svg width="400"></svg>
&#13;