gpt4 book ai didi

d3.js - 如何在 D3JS 中创建跨越不同矩形的渐变?

转载 作者:行者123 更新时间:2023-12-01 09:00:19 26 4
gpt4 key购买 nike

在 D3JS V4 中:假设您有六个矩形。您将如何创建从第一个流到最后一个的渐变?

Gradient across bars

我尝试为矩形创建一个组,然后将 color-gradient-id 添加到该组,但它仍然会导致渐变在每个矩形内单独发生。

最佳答案

您必须将 gradientUnits 设置为 userSpaceOnUse。根据文档,userSpaceOnUse :

...represent values in the coordinate system that results from taking the current user coordinate system in place at the time when the gradient element is referenced

下面是一个没有userSpaceOnUse的demo,结果不是你想要的:

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>

现在是一个使用 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);
<script src="https://d3js.org/d3.v4.min.js"></script>
<svg width="400"></svg>

关于d3.js - 如何在 D3JS 中创建跨越不同矩形的渐变?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43124551/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com