D3过渡:淡入和淡出渐变填充中的颜色

Viv*_*idD 5 javascript svg transition gradient d3.js

在这个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;
        });
    };
}
Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
Run Code Online (Sandbox Code Playgroud)

(与jsfiddle相同的代码)

如何使用颜色淡入淡出而不是不透明?例如,假设我们想要在"淡出"状态下使所有圆圈变灰,并将它们恢复到原始颜色的"正常状态"?你不能只将fill属性转换为颜色值,因为这fill是对<radialGradient>元素的URL引用.

Ame*_*aBR 12

如果您使用的是纯色填充,则将它们转换为灰色然后再返回颜色会很简单 - 只需使用fill属性的d3过渡而不是fill-opacitystroke-opacity属性.

但是,在这种情况下,颜色实际上并不与您选择的元素相关联.相反,它们是在为每个类别创建的<stop>元素中指定的<radialGradient>.(实际上,它们目前是为每个圆圈创建的 - 请参阅下面的注释.)因此,您需要选择这些元素来转换停止颜色.

因为您同时转换给定类别中的所有元素,所以您不需要创建其他渐变元素 - 您只需要一种方法来选择与这些类别关联的渐变,并转换它们.

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

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));
Run Code Online (Sandbox Code Playgroud)

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;
};
Run Code Online (Sandbox Code Playgroud)

要转换渐变,您需要选择渐变而不是圆,并检查它们与哪个聚类相关联.由于渐变元素附加到与节点相同的数据对象,因此可以重用该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);
    });
  };
};
Run Code Online (Sandbox Code Playgroud)

一些说明:

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

  • 为了使颜色去饱和指定的量,我使用d3的颜色函数将颜色转换为HSL(色调饱和度 - 亮度)值,然后乘以饱和度属性.我将它乘以,而不是直接设置它,以防你的任何起始颜色不是100%饱和.但是,我建议使用类似饱和的颜色来获得一致的效果.

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

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

工作片段:

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;
        });
    };
}
Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
Run Code Online (Sandbox Code Playgroud)


注意:

目前,<radialGradient>当您每个群集只需要一个渐变时,您将为每个圆创建一个单独的.通过将clusters数组用作渐变选择的数据而不是数组,可以提高整体性能nodes.但是,您需要id将渐变的值更改为基于群集数据而不是基于节点的索引.


正如Robert Longson在评论中所建议的,使用过滤器将是另一种选择.但是,如果您想要转换效果,则仍需要选择过滤器元素并转换其属性.至少现在(是.当CSS过滤器功能得到更广泛的支持时,您可以直接转换filter: grayscale(0)filter: grayscale(1).