Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SVG - How to crop an image to a circle?

Tags:

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?

like image 726
Eugene Avatar asked Dec 03 '12 20:12

Eugene


People also ask

How do I add an image to a SVG circle?

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.

How do I make an image into a circle?

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.


2 Answers

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.

like image 76
Thomas W Avatar answered Sep 17 '22 20:09

Thomas W


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)"); 
like image 33
martin36 Avatar answered Sep 19 '22 20:09

martin36