Utworzyłem wizualizację D3, która pobiera tablicę danych, tworzy prostokąt dla każdego punktu danych, a następnie wyświetla tekst w prostokącie. Jednak dostałem tylko tekst do wyświetlenia wewnątrz prostokąta, podając współrzędne. Zastanawiam się, w jaki sposób powiedziałbym, aby skupił się na prostym elemencie. Oto kod:Jak wyśrodkować tekst w prostym elemencie w d3?
var elementTags = ["Google", "Amazon", "Wikipedia", "Yahoo!", "Messi", "Ronaldo", "One", "Two", "Three",
"Monkey"];
Kolejna część tworzy tablice Kiedyś pozycjonować prostokąty,
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]
ustawić ich wysokość i szerokość
var elementWidth = 210;
var elementHeight = 60;
tworzenia kontenera SVG i dodać prostokąty,
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");
oraz tutaj jest, gdzie mówię tekstowi, gdzie wyświetlić, to także tam, gdzie potrzebuję pomocy. Chcę, aby tekst automatycznie wyśrodkował się w rectach.
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;});
Dzięki, to było naprawdę przydatne. –