Circular images, with D3

A friend wrote to me today stuck on a d3 problem.  He was looking to create circles with images in them from a set of horizontal and vertical photographs.  The goal was to have the image fill the circle, such that the diameter of the circle was the same as the width or height of the photo, depending on which was smaller.

One of the resources he sent had this jsfiddle from this stackoverflow post. The key here is to define a “pattern” appended to the svg element.

I adapted that fiddle to have additional images, and to show how changing certain parameters gives you a rectangle, circle with white space, or a circle that cropped the image.  The result is here.

Screen Shot 2014-09-24 at 3.08.59 PM

While this example uses hard-coded values, these could be calculated programmatically instead if you just want the center of the circle at the center of the picture.

I also explored using the css border-radius feature as I did here, but that seems to apply only to HTML “img” elements and not to SVG “image”.  I would also have to do something addition in order to get circles instead of ellipses.

This entry was posted in Uncategorized. Bookmark the permalink.

Leave a comment