[英]Why are circle objects located in top left corner of an SVG container?
下面的代碼產生位於容器左上角的圓圈。 我希望它位於與數組值相對應的位置。 這是代碼:
<script>
var data = [ 30, 40, 50 ]
var svg = d3.select("body").append("svg")
.attr("width", 800)
.attr("height", 500)
.style("border", "3px solid black");
var circles = svg.selectAll("g")
.data(data)
.enter()
.append("g");
circles.append("circle")
.attr("cX", function(d) { return d; })
.attr("cY", function(d) { return d; })
.attr("r", 50 )
.style("fill", "steelblue")
circles.append("text")
.text( function(d) { return d; })
</script>
這是DOM:
結果如下:
這里的問題是使用SVG中不存在的cX
和cY
。 屬性是cx
和cy
,均為小寫。
所以這:
circles.append("circle")
.attr("cX", function(d) { return d; })
.attr("cY", function(d) { return d; })
.attr("r", 50 )
.style("fill", "steelblue")
應該是這樣的:
circles.append("circle")
.attr("cx", function(d) { return d; })
.attr("cy", function(d) { return d; })
.attr("r", 50 )
.style("fill", "steelblue")
每次在左上角獲取SVG元素(SVG原點)時,就會懷疑是NaN或設置位置屬性( x
, y
, x1
, y1
, x2
, y2
, cx
, cy
等)時出現的其他問題。 。
這是您的代碼,僅更改cx
和cy
(並更改數據以擴大圈數):
var data = [ 100, 200, 300 ] var svg = d3.select("body").append("svg") .attr("width", 400) .attr("height", 400) .style("border", "3px solid black"); var circles = svg.selectAll("g") .data(data) .enter() .append("g"); circles.append("circle") .attr("cx", function(d) { return d; }) .attr("cy", function(d) { return d; }) .attr("r", 50 ) .style("fill", "steelblue") circles.append("text") .text( function(d) { return d; })
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.