51 javascript d3.js
我创建了一个d3可视化,它接收一个数据数组,为每个数据点创建一个rect,然后在rect中显示文本.但是,我只是通过给出坐标来获得显示在rect内部的文本.我想知道如何告诉它在rect元素中居中.这是代码:
var elementTags = ["Google", "Amazon", "Wikipedia", "Yahoo!", "Messi", "Ronaldo", "One", "Two", "Three",
"Monkey"];
Run Code Online (Sandbox Code Playgroud)
下一部分创建我用来定位rects的数组
var xPosLoop = [0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3];
var yPosLoop = [0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5]
Run Code Online (Sandbox Code Playgroud)
设置它们的宽度和高度
var elementWidth = 210;
var elementHeight = 60;
Run Code Online (Sandbox Code Playgroud)
创建svg容器并添加rects
var svgContainer = d3.select("body") //create container
.append("svg")
.attr("width", 1000)
.attr("height", 1000);
var enterElements = svgContainer.selectAll("rect") //draw elements
.data(elementTags).enter().append("rect")
.attr("x", function(d, i){
return xPosLoop[i]*(elementWidth+25);
})
.attr("height", elementHeight)
.attr("y", function(d, i){
return yPosLoop[i]*(elementHeight+35);
})
.attr("width", elementWidth)
.attr("rx", 4)
.attr("fill", "steelblue")
.attr("stroke", "black")
.attr("stroke-width", 1);
var addText = svgContainer.selectAll("text").data(elementTags).enter().append("text");
Run Code Online (Sandbox Code Playgroud)
这里是我告诉文本在哪里显示的地方,也是我需要帮助的地方.我希望文本自动居中在rects中.
var textElements = addText
.attr("x", function(d, i){
return ((xPosLoop[i]*(elementWidth+25) +elementWidth/2))
})
.attr("y", function(d, i){
return ((yPosLoop[i]*(elementHeight+35)) + elementHeight/2 + 3)
})
.attr("font-family", "Arial Black")
.attr("font-size", "20px")
.attr("fill", "white")
.text(function(d, i){return d;});
Run Code Online (Sandbox Code Playgroud)
mee*_*mit 70
看起来你的代码正确地计算了rect的中心并将文本放在那个点上,除了文本是左对齐的.如果是这样,您只需要更改text-anchor属性以使文本居中.那将是:
textElements.style("text-anchor", "middle")
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
28478 次 |
| 最近记录: |