Custom layout in d3.js?

2019-06-08 04:01发布

How to create custom layout in d3.js ?

Any links or examples would help

I don't want standard layouts d3 uses , want to write my own .

标签: layout d3.js
1条回答
叼着烟拽天下
2楼-- · 2019-06-08 04:09

A layout function could be a simple function that assign coordinates (and any additional data for the drawing like startAngle, endAngle, ...) to your data, and then return an array for the list of nodes. A quick example:

function myLayout(data) {
   var nodes = [];   // or reuse data directly depending on layout
   // for each element of data, assign a x,y coordinate)
   return nodes;
}

var nodes = myLayout(myData);
var g = d3.selectAll('g.node').data(nodes);
g.enter().append('g').attr('class', 'node');
g.attr('transform', function(d) {
   return 'translate(' + d.x + ',' + d.y + ')'});

This is the basic bare bone approach. If you want to follow d3's own code structure, the layout would return a function that does the same as above, but has additional functions to configure it:

function myLayout() {
   var space = 1;
   function compute(data) {
       // same as before
   }
   compute.space = function(s) {
       if (!arguments.length) return space;
       space = s;
       return this;   // chaining
   }
   return compute;
}
var layout = myLayout().space(10);
var nodes = layout(myData);
...
查看更多
登录 后发表回答