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

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

(同样的代码在jsfiddle上)

如何使用颜色来实现淡入淡出,而不是透明度?例如,假设我们希望使所有圆形在“淡出”状态下变为灰色,并在它们的“正常状态”下恢复它们的原始颜色?由于fill是一个对<radialGradient>元素的URL引用,因此无法仅将fill属性作为颜色值进行过渡。


2
你可能想在过渡中应用一个feColorMatrix滤镜。它可以实现与灰度之间的转换。 - Robert Longson
1个回答

12
如果您使用的是纯色填充,那么将其转换为灰色然后再转回颜色就很简单了——只需使用d3过渡中的fill属性而不是fill-opacitystroke-opacity属性。
但是,在这种情况下,颜色实际上并没有与您选择的元素相关联。相反,它们是在为每个类别创建的<radialGradient><stop>元素中指定的(实际上,它们目前是为每个单独的圆形创建的——请参见我的下面的注释)。因此,您需要选择这些元素来过渡停止颜色。
由于您同时转换给定类别中的所有元素,因此不需要创建其他梯度元素——您只需要一种选择与这些类别相关联的渐变的方法,并对其进行过渡。
以下是您创建渐变元素并引用它们为圆形着色的原始代码:
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的颜色函数将颜色转换为HSL(色相-饱和度-亮度)值,然后乘以饱和度属性。我使用乘法而不是直接设置它,以防起始颜色中有任何未饱和的颜色。但是,我建议使用饱和度相似的颜色以获得一致的效果。

  • 在工作示例中,我还更改了您的调色板,以便您不会从一开始就拥有任何灰色。您可能需要创建具有类似饱和度值的自定义调色板。

  • 如果您希望淡出效果的最终值始终是相同的灰色渐变,则可以简化代码 -- 删除所有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;
        });
    };
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>

注意: 目前,您为每个圆形创建了单独的<radialGradient>,但实际上每个集群只需要一个渐变。您可以通过使用clusters数组作为渐变选择的数据而不是nodes数组来提高整体性能。然而,您需要改变渐变的id值,以基于集群数据而不是节点索引。
使用过滤器(如Robert Longson在评论中建议的)也是另一种选择。但是,如果您想要过渡效果,仍然需要选择过滤器元素并转换其属性。至少目前是这样的。当CSS过滤器函数更广泛地支持时,您将能够直接将filter:grayscale(0)过渡到filter:grayscale(1)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接