I am somewhat of a noob to SVG, but I've been playing with D3 and have started to undestand the basics.
What I am trying to achieve is to take a square image and crop it to a circle - which is going to be representing a node on tree I am trying to draw.
I was able to achieve this effect by creating a pattern for each image, then filling the nodes with the pattern. However, the performance on this approach was terrible when there are more than a handfull of nodes on the tree.
So, I am looking for a different approach. I can put a regular "image" object in as my nodes, but they just come out as plain rectangles, obviously, and I'd like to render them as circles. Anyone have any advice on how to either mask/crop the image to achieve the effect I want while maintaining performance?
To display an image inside SVG circle, use the <circle> element and set the clipping path. The <clipPath> element is used to define a clipping path. Image in SVG is set using the <image> element.
Open your image in Photoshop. Convert your background image into an editable layer by double-clicking your Background in the Layers panel, or choose Layer › New › Layer from Background. Select the Elliptical Marquee tool and draw a perfect circle by holding the shift key and dragging your shape into place.
You can use a clip path, like so:
<svg xmlns="http://www.w3.org/2000/svg" width="100%" height="100%"> <clipPath id="clipCircle"> <circle r="50" cx="50" cy="50"/> </clipPath> <rect width="100" height="100" clip-path="url(#clipCircle)"/> </svg>
A circle will be "cut out" from the rectangle.
If you want to generate the same html code as in @Thomas's answer programmatically with D3 you can do the following:
var svg = d3.select("body").append("svg") .attr("width", "100%") .attr("height", "100%"); svg.append("clipPath") .attr("id", "clipCircle") .append("circle") .attr("r", 50) .attr("cx", 50) .attr("cy", 50); svg.append("rect") .attr("width", 100) .attr("height", 100) .attr("clip-path", "url(#clipCircle)");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With