21

Is there a way to display an image inside SVG Circle ?

I tried adding the image inside Svg element but the image does not appear in the circle.

<svg width="100" height="100">
<circle cx="50" cy="50" r="40"stroke="green" stroke-width="4" fill="yellow" />
<img src="starkeen_ane.jpg"/>
 </svg>

Can you help me?

jbutler483
  • 24,074
  • 9
  • 92
  • 145
Amit Verma
  • 40,709
  • 21
  • 93
  • 115

2 Answers2

33

Here is an example elaborating on Havenard's comment above:

<svg width="500" height="250">
    <defs>
        <clipPath id="circleView">
            <circle cx="250" cy="125" r="125" fill="#FFFFFF" />
        </clipPath>
    </defs>
    <image 
      width="500" 
      height="250" 
      xlink:href="https://www.amrita.edu/sites/default/files/news-images/new/news-events/images/l-nov/grass.jpg" 
      clip-path="url(#circleView)"
    />
 </svg>

You don't actually draw a <circle> element with an image inside - instead, define a circular clip path, and set it as the 'clip-path' attribute on the <image> tag.

lawrence-witt
  • 8,094
  • 3
  • 13
  • 32
bags
  • 1,046
  • 7
  • 9
  • 4
    Don't use a mask as a clipPath. Use a clipPath, that's why a clipPath exists. A mask is a raster operation, uses lots of memory and is slow. – Robert Longson Jun 17 '15 at 16:42
  • D'oh. Good point, Robert. Updated example. https://developer.mozilla.org/en-US/docs/Web/SVG/Tutorial/Clipping_and_masking. – bags Jun 17 '15 at 16:42
  • Very nice. FYI, it seems that the fill attr does nothing here. – Turbo Sep 06 '18 at 21:04
1

It is maybe not the best way to do it. but it works very good. The thing you can do it place it to a relative position and edit top and left properties so you image is in the center of your svg image. Also important is to place it outside your svg-tag.

img {
  position: relative;
  top: -30px;
  left: -70px;
}
<svg width="100" height="100">
<circle cx="50" cy="50" r="40"stroke="green" stroke-width="4" fill="yellow" />
 </svg>
<img src="https://i.stack.imgur.com/vxCmj.png"/>
H. Pauwelyn
  • 13,575
  • 26
  • 81
  • 144
  • 5
    And then you have a white space padded under the `` with the same height of the image. Thats how bad it is to abuse `position: relative` for ordinary things. – Havenard Jun 17 '15 at 16:29