【问题标题】:D3 transition: Fading in and out the colors within a gradient fillD3 过渡:渐变填充中的颜色淡入和淡出
【发布时间】:2023-03-27 16:25:02
【问题描述】:

在这个 D3 图中,圆圈填充了径向渐变,并且改变不透明度用于淡入和淡出:

var width = 400,
    height = 400,
    padding = 1.5, // separation between same-color nodes
    clusterPadding = 6, // separation between different-color nodes
    maxRadius = 12;

var n = 200, // total number of nodes
    m = 10; // number of distinct clusters

var color = d3.scale.category10()
    .domain(d3.range(m));

// The largest node for each cluster.
var clusters = new Array(m);

var nodes = d3.range(n).map(function() {
    var i = Math.floor(Math.random() * m),
        r = Math.sqrt((i + 1) / m * -Math.log(Math.random())) * maxRadius,
        d = {cluster: i, radius: r};
    if (!clusters[i] || (r > clusters[i].radius)) clusters[i] = d;
    return d;
});

// Use the pack layout to initialize node positions.
d3.layout.pack()
    .sort(null)
    .size([width, height])
    .children(function(d) { return d.values; })
    .value(function(d) { return d.radius * d.radius; })
    .nodes({values: d3.nest()
        .key(function(d) { return d.cluster; })
        .entries(nodes)
    });

var force = d3.layout.force()
    .nodes(nodes)
    .size([width, height])
    .gravity(.02)
    .charge(0)
    .on("tick", tick)
    .start();

var svg = d3.select("body").append("svg")
    .attr("width", width)
    .attr("height", height);

var grads = svg.append("defs").selectAll("radialGradient")
    .data(nodes)
   .enter()
    .append("radialGradient")
    .attr("gradientUnits", "objectBoundingBox")
    .attr("cx", 0)
    .attr("cy", 0)
    .attr("r", "100%")
    .attr("id", function(d, i) { return "grad" + i; });

grads.append("stop")
    .attr("offset", "0%")
    .style("stop-color", "white");

grads.append("stop")
    .attr("offset", "100%")
    .style("stop-color",  function(d) { return color(d.cluster); });

var node = svg.selectAll("circle")
    .data(nodes)
   .enter()
    .append("circle")
    .style("fill", function(d, i) {
        return "url(#grad" + i + ")";
    })
    // .style("fill", function(d) { return color(d.cluster); })
    .call(force.drag)
    .on("mouseover", fade(.1))
    .on("mouseout", fade(1));

node.transition()
    .duration(750)
    .delay(function(d, i) { return i * 5; })
    .attrTween("r", function(d) {
      var i = d3.interpolate(0, d.radius);
      return function(t) { return d.radius = i(t); };
    });


function fade(opacity) {
    return function(d) {
        node.transition().duration(1000)
            .style("fill-opacity", function(o) {
                return isSameCluster(d, o) ? 1 : opacity;
            })
            .style("stroke-opacity", function(o) {
                return isSameCluster(d, o) ? 1 : opacity;
            });
    };
};

function isSameCluster(a, b) {
     return a.cluster == b.cluster;
};


function tick(e) {
    node
        .each(cluster(10 * e.alpha * e.alpha))
        .each(collide(.5))
        .attr("cx", function(d) { return d.x; })
        .attr("cy", function(d) { return d.y; });
}

// Move d to be adjacent to the cluster node.
function cluster(alpha) {
    return function(d) {
        var cluster = clusters[d.cluster];
        if (cluster === d) return;
        var x = d.x - cluster.x,
            y = d.y - cluster.y,
            l = Math.sqrt(x * x + y * y),
            r = d.radius + cluster.radius;
        if (l != r) {
            l = (l - r) / l * alpha;
            d.x -= x *= l;
            d.y -= y *= l;
            cluster.x += x;
            cluster.y += y;
        }
    };
}

// Resolves collisions between d and all other circles.
function collide(alpha) {
    var quadtree = d3.geom.quadtree(nodes);
    return function(d) {
        var r = d.radius + maxRadius + Math.max(padding, clusterPadding),
            nx1 = d.x - r,
            nx2 = d.x + r,
            ny1 = d.y - r,
            ny2 = d.y + r;
        quadtree.visit(function(quad, x1, y1, x2, y2) {
            if (quad.point && (quad.point !== d)) {
                var x = d.x - quad.point.x,
                    y = d.y - quad.point.y,
                    l = Math.sqrt(x * x + y * y),
                    r = d.radius + quad.point.radius +
                       (d.cluster === quad.point.cluster ? padding : clusterPadding);
                if (l < r) {
                    l = (l - r) / l * alpha;
                    d.x -= x *= l;
                    d.y -= y *= l;
                    quad.point.x += x;
                    quad.point.y += y;
                }
            }
            return x1 > nx2 || x2 < nx1 || y1 > ny2 || y2 < ny1;
        });
    };
}
&lt;script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"&gt;&lt;/script&gt;

(Same code as a jsfiddle)

如何使用颜色来淡入淡出,而不是不透明度?例如,假设我们想让所有圆圈在“淡出”状态下变灰,并在“正常状态”下将它们恢复到原来的颜色?你不能只是将fill属性转换为颜色值,因为 fill 是对 &lt;radialGradient&gt; 元素的 URL 引用。

【问题讨论】:

  • 您可能希望在过渡中应用 feColorMatrix 滤镜。这可以转换为/从灰度转换。

标签: javascript svg d3.js transition gradient


【解决方案1】:

如果您使用纯色填充,可以直接将它们转换为灰色,然后再转换回彩色 - 只需使用 fill 属性的 d3 转换,而不是 fill-opacitystroke-opacity 属性。

但是,这种情况下的颜色实际上并不与您选择的元素相关联。相反,它们是在为每个类别创建的&lt;radialGradient&gt;&lt;stop&gt; 元素中指定的。 (实际上,它们目前是为每个单独的圆圈创建的——请参阅下面的注释。)因此,您需要选择这些元素来过渡停止颜色。

因为您要同时转换给定类别中的所有元素,所以您不需要创建额外的渐变元素 - 您只需要一种方法来选择与这些类别相关联的渐变并进行转换。

这是您创建渐变元素并引用它们为圆圈着色的原始代码:

var grads = svg.append("defs").selectAll("radialGradient")
    .data(nodes)
   .enter()
    .append("radialGradient")
    .attr("gradientUnits", "objectBoundingBox")
    .attr("cx", 0)
    .attr("cy", 0)
    .attr("r", "100%")
    .attr("id", function(d, i) { return "grad" + i; });

grads.append("stop")
    .attr("offset", "0%")
    .style("stop-color", "white");

grads.append("stop")
    .attr("offset", "100%")
    .style("stop-color",  function(d) { return color(d.cluster); });

var node = svg.selectAll("circle")
    .data(nodes)
   .enter()
    .append("circle")
    .style("fill", function(d, i) {
        return "url(#grad" + i + ")";
    })
    .call(force.drag)
    .on("mouseover", fade(.1))
    .on("mouseout", fade(1));

您当前使用的fade() 函数会为每个元素生成一个单独的事件处理函数,然后根据它们是否在与收到事件的圈子相同的集群:

function fade(opacity) {
    return function(d) {
        node.transition().duration(1000)
            .style("fill-opacity", function(o) {
                return isSameCluster(d, o) ? 1 : opacity;
            })
            .style("stroke-opacity", function(o) {
                return isSameCluster(d, o) ? 1 : opacity;
            });
    };
};

function isSameCluster(a, b) {
     return a.cluster == b.cluster;
};

要转换渐变,您需要选择 渐变 而不是圆形,并检查它们与哪个集群相关联。由于渐变元素与节点附加到相同的数据对象,因此您可以重用isSameCluster() 方法。您只需要更改fade() 方法中的内部函数:

function fade(saturation) {
  return function(d) {
    grads.transition().duration(1000)
    .select("stop:last-child") //select the second (colored) stop
    .style("stop-color", function(o) {

      var c = color(o.cluster);
      var hsl = d3.hsl(c);

      return isSameCluster(d, o) ? 
        c : 
        d3.hsl(hsl.h, hsl.s*saturation, hsl.l);
    });
  };
};

一些注意事项:

  • 为了在渐变中选择正确的停止元素,我使用了:last-child 伪类。您也可以在创建停止元素时只给它们一个普通的 CSS 类。

  • 要将颜色去饱和指定的量,我使用d3's color functions 将颜色转换为 HSL(色相-饱和度-亮度)值,然后乘以饱和度属性。我将它相乘,而不是直接设置它,以防您的任何起始颜色不是 100% 饱和。不过,我建议使用类似饱和度的颜色来获得一致的效果。

  • 在工作示例中,我还更改了您的调色板,以便您一开始不会有任何灰色(无论如何,对于前 10 个集群)。您可能需要为所有颜色创建一个具有相似饱和度值的自定义调色板。

  • 如果您希望淡出效果的最终值始终是相同的灰色渐变,您可以稍微简化代码 - 删除所有 hsl 计算,并使用布尔参数而不是一个数字 saturation 值。或者甚至只有两个函数,一个是重置所有颜色,而不需要测试哪个簇是哪个,另一个是测试簇并将值相应地设置为灰色。

工作sn-p:

var width = 400,
    height = 400,
    padding = 1.5, // separation between same-color nodes
    clusterPadding = 6, // separation between different-color nodes
    maxRadius = 12;

var n = 200, // total number of nodes
    m = 10; // number of distinct clusters

var color = d3.scale.category20()
    .domain(d3.range(m));

// The largest node for each cluster.
var clusters = new Array(m);

var nodes = d3.range(n).map(function() {
    var i = Math.floor(Math.random() * m),
        r = Math.sqrt((i + 1) / m * -Math.log(Math.random())) * maxRadius,
        d = {cluster: i, radius: r};
    if (!clusters[i] || (r > clusters[i].radius)) clusters[i] = d;
    return d;
});

// Use the pack layout to initialize node positions.
d3.layout.pack()
    .sort(null)
    .size([width, height])
    .children(function(d) { return d.values; })
    .value(function(d) { return d.radius * d.radius; })
    .nodes({values: d3.nest()
        .key(function(d) { return d.cluster; })
        .entries(nodes)
    });

var force = d3.layout.force()
    .nodes(nodes)
    .size([width, height])
    .gravity(.02)
    .charge(0)
    .on("tick", tick)
    .start();

var svg = d3.select("body").append("svg")
    .attr("width", width)
    .attr("height", height);

var grads = svg.append("defs").selectAll("radialGradient")
    .data(nodes)
   .enter()
    .append("radialGradient")
    .attr("gradientUnits", "objectBoundingBox")
    .attr("cx", 0)
    .attr("cy", 0)
    .attr("r", "100%")
    .attr("id", function(d, i) { return "grad" + i; });

grads.append("stop")
    .attr("offset", "0%")
    .style("stop-color", "white");

grads.append("stop")
    .attr("offset", "100%")
    .style("stop-color",  function(d) { return color(d.cluster); });

var node = svg.selectAll("circle")
    .data(nodes)
   .enter()
    .append("circle")
    .style("fill", function(d, i) {
        return "url(#grad" + i + ")";
    })
    // .style("fill", function(d) { return color(d.cluster); })
    .call(force.drag)
    .on("mouseover", fade(.1))
    .on("mouseout", fade(1));

node.transition()
    .duration(750)
    .delay(function(d, i) { return i * 5; })
    .attrTween("r", function(d) {
      var i = d3.interpolate(0, d.radius);
      return function(t) { return d.radius = i(t); };
    });


function fade(saturation) {
  return function(d) {
    grads.transition().duration(1000)
    .select("stop:last-child") //select the second (colored) stop
    .style("stop-color", function(o) {

      var c = color(o.cluster);
      var hsl = d3.hsl(c);

      return isSameCluster(d, o) ? 
        c : 
      d3.hsl(hsl.h, hsl.s*saturation, hsl.l);
    });
  };
};

function isSameCluster(a, b) {
  return a.cluster == b.cluster;
};


function tick(e) {
    node
        .each(cluster(10 * e.alpha * e.alpha))
        .each(collide(.5))
        .attr("cx", function(d) { return d.x; })
        .attr("cy", function(d) { return d.y; });
}

// Move d to be adjacent to the cluster node.
function cluster(alpha) {
    return function(d) {
        var cluster = clusters[d.cluster];
        if (cluster === d) return;
        var x = d.x - cluster.x,
            y = d.y - cluster.y,
            l = Math.sqrt(x * x + y * y),
            r = d.radius + cluster.radius;
        if (l != r) {
            l = (l - r) / l * alpha;
            d.x -= x *= l;
            d.y -= y *= l;
            cluster.x += x;
            cluster.y += y;
        }
    };
}

// Resolves collisions between d and all other circles.
function collide(alpha) {
    var quadtree = d3.geom.quadtree(nodes);
    return function(d) {
        var r = d.radius + maxRadius + Math.max(padding, clusterPadding),
            nx1 = d.x - r,
            nx2 = d.x + r,
            ny1 = d.y - r,
            ny2 = d.y + r;
        quadtree.visit(function(quad, x1, y1, x2, y2) {
            if (quad.point && (quad.point !== d)) {
                var x = d.x - quad.point.x,
                    y = d.y - quad.point.y,
                    l = Math.sqrt(x * x + y * y),
                    r = d.radius + quad.point.radius +
                       (d.cluster === quad.point.cluster ? padding : clusterPadding);
                if (l < r) {
                    l = (l - r) / l * alpha;
                    d.x -= x *= l;
                    d.y -= y *= l;
                    quad.point.x += x;
                    quad.point.y += y;
                }
            }
            return x1 > nx2 || x2 < nx1 || y1 > ny2 || y2 < ny1;
        });
    };
}
&lt;script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"&gt;&lt;/script&gt;

注意:

目前,您正在为每个圆圈创建一个单独的&lt;radialGradient&gt;,而实际上每个集群只需要一个渐变。您可以通过使用 clusters 数组而不是 nodes 数组作为渐变选择的数据来提高整体性能。但是,您需要将梯度的 id 值更改为基于集群数据而不是节点的索引。


按照 Robert Longson 在 cmets 中的建议,使用过滤器是另一种选择。但是,如果您想要一个过渡效果,您仍然需要选择过滤器元素并过渡它们的属性。至少现在。当CSS filter functions 得到更广泛的支持时,您可以直接将filter: grayscale(0) 转换为filter: grayscale(1)

【讨论】:

    猜你喜欢
    • 2012-02-04
    • 2020-08-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-02
    • 2020-04-18
    • 2015-12-09
    相关资源
    最近更新 更多