javascript 如何在d3的矩形元素中居中文本?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16620267/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to center text in a rect element in d3?
提问by meetamit
I have created a d3 visualization that takes an array of data, creats a rect for each data point, and then displays the text in the rect. However, I have only gotten the text to display inside of the rect by giving it coordinates. I am wondering how I would tell it to center itself in the rect element. Here is the code:
我创建了一个 d3 可视化,它接受一组数据,为每个数据点创建一个矩形,然后在矩形中显示文本。但是,我只是通过给它坐标来让文本显示在矩形内。我想知道如何告诉它以 rect 元素为中心。这是代码:
var elementTags = ["Google", "Amazon", "Wikipedia", "Yahoo!", "Messi", "Ronaldo", "One", "Two", "Three",
"Monkey"];
The next part creates arrays I used to position the 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]
set their width and height
设置它们的宽度和高度
var elementWidth = 210;
var elementHeight = 60;
create the svg container and add rects
创建 svg 容器并添加矩形
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");
and here is where i tell the text where to display, it's also where I need help. I want the text to center itself in the rects automatically.
这是我告诉文本在哪里显示的地方,这也是我需要帮助的地方。我希望文本自动在矩形中居中。
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;});
回答by meetamit
It seems that your code properly computes the center of the rect and places the text at that point, except that the text is left aligned. If so, you just need to change the text-anchor
property to center the text. That would be:
似乎您的代码正确计算了矩形的中心并将文本放置在该点,除了文本左对齐。如果是这样,您只需要更改text-anchor
属性以将文本居中。那将是:
textElements.style("text-anchor", "middle")