我想用d3制作一个传奇。下一个元素的位置应取决于前一个元素。
对于ex,我有一个这样的数组:
var data =["Saudi - Arabia","Russia","Asia","United - States","Australia"];
这是我的javascript代码:
var com_x=0;
var com_y=0;
var legend = d3.select("#chart").append("svg")
.attr("class", "legend")
.attr("width", r*3)
.attr("height", r *1.5)
.selectAll("g")
.data(data)
.enter().append("g")
.attr( "transform", function(d,i) {
var currentElementLength = data[i].length;
var nextElementLength = 0;
if( i < data.length-1)
{
//alert(i)
nextElementLength = data[i+1].length;
}
//alert(currentElementLength+" "+nextElementLength+" "+data[i+1]);
if((currentElementLength+nextElementLength) > 16)
{
x1 = com_x
y1 = com_y
com_y = com_y+20
//alert("One "+i+" "+x1+" "+y1);
return "translate(" + x1 + "," + y1 + ")"
}
else
{
x1 = com_x
y1 = com_y
com_x = com_x+80
//alert("Two "+i+" "+x1+" "+y1);
return "translate(" + x1 + "," + y1 + ")"
}
} );
legend.append("rect")
/* .attr("x",20)
.attr("y",-50) */
.attr("width", 13)
.attr("height", 13)
.attr("transform", "translate(10,10)")
.style("fill", function(d, i) { return color(i); });
legend.append("text")
/* .attr("x", 42)
.attr("y", -41) */
.attr("dx", -7)
.attr("dy", ".20em")
.style("font-size", "14px")
.attr("transform", "translate(33,20)")
.text(function(d,i) { return data[i]; });
我好像,当前元素+下一个元素大于16,下一个元素应该显示在下一行。对于前两行,我得到了正确的位置。但对于第三和第四行,x位置出错。请查看以下链接。
这是my chart!
他们有什么办法动态而不是硬编码?
任何帮助!!
答案 0 :(得分:0)
当您检测到元素的宽度太宽并且将com_y
增加到下一行的位置时,您不会将com_x
重置回0
。这就是为什么第3行及以后的位置错误。
if((currentElementLength+nextElementLength) > 16)
{
x1 = com_x
y1 = com_y
com_y = com_y+20
com_x = 0 // <<---- add this line
return "translate(" + x1 + "," + y1 + ")"
}
更一般地说,您可能会发现如果使用非固定宽度字体,使用字符中文本的长度会导致一些意外结果;有些人物比其他人更广泛。如果这成为问题,您可能需要计算文本的像素宽度。有许多问题涉及该特定主题。例如:SVG get text element width