Reputation: 3051
I would like to know how to obtain the central point of a circle to place my marker dynamically. In my real project, my circle can be in a random position within the svg, and I must locate my marker so that the bottom tip of this, is located in the center of the circle.
How can I do this?
<body>
<script type="text/javascript">
const svg = d3.select("body").append("svg").attr("width",1000).attr("height",1000);
svg.append("circle").attr("r",5).attr("cx",100).attr("cy",200).style("stroke","#FF0000");
var widthMarker=50;
var img = svg.append("svg:image")
.attr("xlink:href", "marker.svg")
.attr("width", widthMarker)
.attr("height", widthMarker)
.attr("x", 228)
.attr("y",53)
</script>
</body>
http://plnkr.co/edit/vFtJkZ1GKmyGYIUR0wXR?p=preview
Upvotes: 2
Views: 2295
Reputation: 102194
Firstly, name your selections:
var circle = svg.append("circle")
.attr("r", 5)
.attr("cx", 100)
.attr("cy", 200)
.style("stroke", "#FF0000");
That being said, back to your question:
First, use getBBox()
to get the circle's coordinates (provided that there is no translation), assuming that you don't know, for whatever reason, its location (that is, neither its cx
nor its cy
values):
var circleBox = circle.node().getBBox();
Then, use those coordinates to set the x
and y
positions:
.attr("x", circleBox.x + circleBox.width/2 - widthMarker/2)
.attr("y",circleBox.y + circleBox.height/2 - widthMarker)
Here is the updated Plunker: http://plnkr.co/edit/DYlJsUhrF1OgoChq927L?p=preview
Upvotes: 2
Reputation: 108537
Let cx
represent the circle x position, cy
the circle y position and mw
the width of the marker, the formula is:
markerX = cx - mw / 2;
markerY = cy - mw;
Updated plunker:
var cx = 100,
cy = 200;
svg.append("circle").attr("r", 5).attr("cx", cx).attr("cy", cy).style("stroke", "#FF0000");
var mw = 50;
var img = svg.append("svg:image")
.attr("xlink:href", "marker.svg")
.attr("width", mw)
.attr("height", mw)
.attr("x", cx - mw / 2)
.attr("y", cy - mw);
Upvotes: 1