【问题标题】:Draw a D3 circle with gradient colours用渐变色画一个 D3 圆
【发布时间】:2013-12-30 09:54:45
【问题描述】:

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

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

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

【问题讨论】:

    标签: javascript d3.js svg gradient geometry


    【解决方案1】:

    您必须先在 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)');
    

    带有完整示例的jsFiddle。有关如何在MDN Tutorial 中定义 SVG 渐变的更多详细信息。生成的图像:

    【讨论】:

      【解决方案2】:

      看看这段代码sn-p:

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

      它支持使用渐变绘制 SVG 圆圈(并通过这样做实现 3D 外观效果)并且基于 SVG radial gradients


      为每个节点定义一个梯度:

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

      然后,而不是行:

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

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

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-10-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-12-26
        • 2020-11-24
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多