Reputation: 83
I am using Javascript to create an SVG element that contains a circle with a radius and a stroke thickness. The size and thickness may vary. I'm trying to create a square shaped div that would fit inside this SVG circle, so that I may add content inside the circle.
You can imagine the content to be anything from a text containing information about the circle, an anchor, or a button.
The rectangle must fit in the circle in so that all content is wrapped, and if there is no space, the content will be removed.
<!-- A minified example of what the Javascript outputs -->
<svg viewBox="0 0 80 80" width="80" height="80">
<circle cx="40" cy="40" r="35"></circle>
</svg>
My main question is if it's possible to add this solely to the SVG element, and using something like the styling: left: 10%; top: 10%; width:50%; height: 50%
, or if this would require more advanced CSS or Javascript trickery.
It's important to also mention that my circle has a radius of (svgWidth / 2) * 0.875
that is set from within the Javascript code.
Upvotes: 0
Views: 613
Reputation: 511
I believe this is what you are looking for. You can resize the SVG and see everything resizes accordingly.
.container {
position: absolute;
top: 0;
bottom: 0;
right: 0;
left: 0;
background-color: #fff;
display: flex;
align-items: center;
justify-content: center;
}
.container svg {
fill: #dedede;
stroke: #000;
width: 200px;
height: 200px;
overflow: visible;
background-color: lightblue;
border: 1px solid blue;
}
.container svg g > .text-holder {
background-color: lightcoral;
}
.container svg g > .text-holder > p {
font-size: 12px;
}
.container svg g > circle {
cx: 50%;
cy: 50%;
r: 50%;
}
.container svg g > rect {
stroke: #f00;
x: 15%;
y: 15%;
width: 70%;
height: 70%;
}
<div class="container">
<svg viewBox="0 0 80 80">
<g>
<circle></circle>
<rect></rect>
<foreignObject class="text-holder" x="15%" y="15%" width="70%" height="70%">
<p xmlns="http://www.w3.org/1999/xhtml" style="font-size: 12px;">Text goes here</p>
</foreignObject>
</g>
</svg>
</div>
Upvotes: 2
Reputation: 83
Okay, thanks to @Sergiu I found the right mathematical equation to solve it, this was the primary issue. The code below is taken out of my Javascript code and shows how I create a rect
that fits exactly like the square my image.
var squareSize = Math.sqrt(2) * radius - circleStrokeThickness;
var squareCenter = (svgWidth - squareSize) / 2;
this.rectangleContent = document.createElementNS('http://www.w3.org/2000/svg', 'rect');
this.rectangleContent.setAttribute('x', squareCenter);
this.rectangleContent.setAttribute('y', squareCenter);
this.rectangleContent.setAttribute('width', squareSize);
this.rectangleContent.setAttribute('height', squareSize);
this.rectangleContent = $(this.rectangleContent).appendTo(this.svg);
This is not a div but it already answers all of the questions I had about the placement of the div.
Upvotes: 3