0

好的,所以我想根据数据使用 D3 绘制弧线。但是,当我尝试将值作为函数传递时,它会失败,如果我将它作为变量传递,它会起作用。

检查小提琴:http: //jsfiddle.net/paulocoelho/WyABt/1/

这是代码:

var a = [[0.1, 0.4],[0.4,0.56],[0.56,1]];

var cfg = {
    w:200,
    h:200
};

var g = d3.select("#testdiv").append("svg").attr("width", cfg.w).attr("height", cfg.h).append("g")

var arct = d3.svg.arc()
        .innerRadius(cfg.h / 4)
        .outerRadius(cfg.h / 3)
        .startAngle(0)
        .endAngle(Math.PI);

// This one works
var path = g.selectAll("circleArcs").data(a).enter().append("svg:path")
    .attr("d", arct)
    .style("fill","blue")
    .attr("transform", "translate("+cfg.w/2+","+cfg.h/2+")");

// This one does not!
var path2 = g.selectAll("circleArcs").data(a).enter().append("svg:path")
    .attr("d", function(d,i){ return arct;})
    .style("fill","green");

所以,现在数据没有连接,但我的意思是我传递完全相同的对象arct,但是通过函数返回的对象不起作用......

4

1 回答 1

1

arct在第一个中使用时path,d3.attr调用该arct函数。

selection.attr(名称[,值]

...如果 value 是一个函数,则为每个选定元素(按顺序)评估该函数[强调添加]...

但是 in path2,当在外部arct函数内部返回时,运行外部函数,但内部函数不会自动被调用。.attrarct

这是一个修改后的小提琴......

http://jsfiddle.net/pnQKY/2/

var path2 = g.selectAll("circleArcs").data(a).enter().append("svg:path")
    .attr("d", function(){ 
        // console.log( typeof arct ); // "function": returns function reference, which does not get invoked inside of the outer function
        // console.log( typeof arct() ); // "string": returns value of invoked function 
        return arct();
     })
    .style("fill","green");
     ...

希望这有助于作为一个起点。

于 2013-05-20T22:19:16.737 回答