javascript 用渐变色绘制一个 D3 圆

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20837147/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 19:25:33  来源:igfitidea点击:

Draw a D3 circle with gradient colours

javascriptd3.jssvggradientgeometry

提问by user2637905

How to draw a circle with gradient color? Say, a gradient from yellow to blue.

如何画一个渐变色的圆?比如说,从黄色到蓝色的渐变。

Normally, to create a circle in yellow we can use the following code:

通常,要创建一个黄色的圆圈,我们可以使用以下代码:

var cdata=[50,40];
var xscale=40;
var xspace =50;
var yscale=70;

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

var circle = svg.selectAll("circle")
    .data(cdata)
   .enter()
    .append("circle");

var circleattr = circle
    .attr("cx", function(d) {
        xscale = xscale+xspace;
        return xscale;
    })
    .attr("cy", function(d) {
        yscale=yscale+xspace+10;
        return yscale;
    })
    .attr("r", function(d) {
        return d;
    })
    .style("fill","yellow");

回答by Pablo Navarro

You have to define the gradient in the SVG first, and then fill the circle with an SVG link to the gradient element.

您必须首先在 SVG 中定义渐变,然后用指向渐变元素的 SVG 链接填充圆圈。

// Define the gradient
var gradient = svg.append("svg:defs")
    .append("svg:linearGradient")
    .attr("id", "gradient")
    .attr("x1", "0%")
    .attr("y1", "0%")
    .attr("x2", "100%")
    .attr("y2", "100%")
    .attr("spreadMethod", "pad");

// Define the gradient colors
gradient.append("svg:stop")
    .attr("offset", "0%")
    .attr("stop-color", "#a00000")
    .attr("stop-opacity", 1);

gradient.append("svg:stop")
    .attr("offset", "100%")
    .attr("stop-color", "#aaaa00")
    .attr("stop-opacity", 1);

// Fill the circle with the gradient
var circle = svg.append('circle')
    .attr('cx', width / 2)
    .attr('cy', height / 2)
    .attr('r', height / 3)
    .attr('fill', 'url(#gradient)');

A jsFiddlewith the complete example. More details on how to define SVG gradients in the MDN Tutorial. The resulting image:

的jsfiddle与完整的例子。有关如何在MDN 教程中定义 SVG 渐变的更多详细信息。结果图像:

Circle with gradient, created in D3

带渐变的圆,在 D3 中创建

回答by VividD

Take a look at this code snippet:

看看这个代码片段:

var width = 500,
    height = 500,
    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);

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 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>

It contains support for drawing SVG circles with gradient (and achieving a 3D look-and-feel effect by doing this) and is based on SVG radial gradients.

它包含对绘制带有渐变的 SVG 圆的支持(并通过这样做实现 3D 观感效果)并且基于SVG 径向渐变



For each node, a gradient is defined:

对于每个节点,定义了一个梯度:

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); });

Then, instead of line:

然后,而不是行:

.style("fill", function(d) { return color(d.cluster); })

this line is added in the code that creates circles:

在创建圆圈的代码中添加了这一行:

.attr("fill", function(d, i) {
    return "url(#grad" + i + ")";
})

This produces this effect:(animated gif that I used has some limitations for number of colors, so gradients are not smooth as in real example)

这会产生这种效果:(我使用的动画 gif 对颜色数量有一些限制,因此渐变不像实际示例中那样平滑)

enter image description here

在此处输入图片说明