0

我使用 d3 已经有一段时间了,但每次我想对 d3 选择应用翻译时,我都会这样做:

 var svg = d3
        .select("svg")
        .attr("transform", "translate(0,$1)".replace("$1", "" + (someHeight)))

注意:someHeight通常是一个计算,否则我会使用字符串连接,我只是觉得这样读起来更好。

我一直在尝试寻找是否有更好的方法来设置转换,可能是通过其他 API 而不是attr

让我知道这个问题是否需要更好地解释。

亲切的问候。

4

2 回答 2

2

You can use the d3.transform function to parse this attribute and manipulate it in a nicer way:

var t = d3.select("svg").attr("transform");
t.translate[1] = someHeight;
d3.select("svg").attr("transform", t.toString);

You can of course also use pure Javascript to set the attribute:

d3.select("svg").each(function() { this.setAttribute("transform", ...); });

That's not nicer though. I guess calling a single four-letter function is at least about as succinct as it gets.

于 2013-10-03T13:12:45.100 回答
0

我想一个折衷的解决方案只是为每个转换函数编写一个简单的实用程序,对于这种情况

var translateXY = function(x,y) {
  return "translate(" + x + "," + y + ")"
}

然后在需要时使用它:

d3.attr("transform", translate(x,y))

感谢您的回答。

于 2013-10-03T13:50:53.673 回答