创建自定义d3生成器

Sta*_*ers 1 javascript d3.js

所以我可以创建一个区域生成器:

d3.svg.area()
Run Code Online (Sandbox Code Playgroud)

......或线路生成器:

d3.svg.line()
Run Code Online (Sandbox Code Playgroud)

但是有可能创建自己的发电机,例如圆形发电机吗?:

d3.svg.circle()
Run Code Online (Sandbox Code Playgroud)

我只想使用这个清晰的语法:

// don't know if it's possible to do this...
svg.append('path').datum(data).attr({
  d: circleGenerator
})
Run Code Online (Sandbox Code Playgroud)

而不是使用奇怪的(至少对我来说)vg.selectAll('circle').data(data).enter().append('circle').attr()方法链就地创建一个圆:

// the correct but messy way to do it...
svg.selectAll('circle').data(data).enter().append('circle').attr({
  cx: function(d){ return d.x },
  cy: function(d){ return d.y },
  r: 3,
  transform: 'translate(100,200)'
});
Run Code Online (Sandbox Code Playgroud)

我希望能够将所有这些逻辑提取到生成器中,并通过它传递信息 datum

Jos*_*osh 8

这当然是可能的,你需要从头创建这个生成器,即:

function circleGen() {
  //set defaults
  var r = function(d) { return d.radius; },
      x = function(d) { return d.x; },
      y = function(d) { return d.y; };

  //returned function to generate circle path
  function circle(d) {
    var cx = d3.functor(x).call(this, d),
        cy = d3.functor(y).call(this, d),
        myr = d3.functor(r).call(this, d);

    return "M" + cx + "," + cy + " " +
           "m" + -myr + ", 0 " +
           "a" + myr + "," + myr + " 0 1,0 " + myr*2  + ",0 " +
           "a" + myr + "," + myr + " 0 1,0 " + -myr*2 + ",0Z";
  }

  //getter-setter methods
  circle.r = function(value) {
    if (!arguments.length) return r; r = value; return circle;
  };  
  circle.x = function(value) {
    if (!arguments.length) return x; x = value; return circle;
  };  
  circle.y = function(value) {
    if (!arguments.length) return y; y = value; return circle;
  };

  return circle;
}
Run Code Online (Sandbox Code Playgroud)

然后,它可以按照您的描述使用:

var myC = circleGen()
   .x(function(d) { return d.x; })
   .y(function(d) { return d.y; })
   .r(function(d) { return d.r; });

var data = [
  {x: 150, y: 100, r: 10, fill: "green"},
  {x: 200, y: 150, r: 5, fill: "red"},
  {x: 100, y: 250, r: 25, fill: "blue"}
];

svg.selectAll("path.circle")
    .data(data)
  .enter().append("path")
    .attr("class", "circle")
    .attr("d", myC)
    .style("fill", function(d) { return d.fill; });
Run Code Online (Sandbox Code Playgroud)

完整示例:http://bl.ocks.org/jsl6906/cb75852db532cee284ed