Home > Back-end >  How can I put a background image on a circle component?
How can I put a background image on a circle component?

Time:12-17

I wrote the code below which makes for me a circle with a partial red and green border. It was shown in the first photo.

Now my question is how can I fill the circle inside with a picture? I mean something like background-image: url("");. Can I do the same with fill attribute (now it is transparent)? The circle should look like on the second picture (the picture is just an example). I am using React and styled-components.

const Wrapper = styled.svg`
  position: relative;
`;

const BottomCircle = styled.circle`
  stroke: ${({ theme }) => theme.red};
  stroke-width: 5px;
  stroke-dasharray: 440;
  stroke-dashoffset: 0;
  fill: transparent;
`;

const TopCircle = styled.circle`
  stroke: ${({ theme }) => theme.green};
  stroke-width: 5px;
  stroke-dasharray: 440;
  stroke-dashoffset: 250;
  fill: transparent;
`;

const Holder = styled.g``;

<Wrapper width="200" height="200">
    <Holder transform="rotate(-90 100 100)">
       <BottomCircle r="70" cx="100" cy="100"></BottomCircle>
       <TopCircle r="70" cx="100" cy="100"></TopCircle>
    </Holder>
</Wrapper>

enter image description here

enter image description here

CodePudding user response:

This is how I would approach this. Use a div with a conic gradient with an image on top to mask it.

const Avatar = styled.div`
  width: 200px;
  height: 200px;
  position: relative;
  border-radius: 50%;
  background: ${({ Progress }) => {
    if (Progress)
      return `conic-gradient(red ${(Progress / 100) * 360}deg, yellow ${
        (Progress / 100) * 360
      }deg 360deg)`;
  }};

  &:before {
    content: "";
    position: absolute;
    top: 5px;
    left: 5px;
    border-radius: 50%;
    width: calc(100% - 10px);
    height: calc(100% - 10px);
    background-image: ${({ ImageSrc }) => {
      if (ImageSrc) return `url(${ImageSrc})`;
    }};
    background-position: center;
    background-size: contain;
  }
`;

<Avatar Progress={80} ImageSrc="https://i.pinimg.com/474x/ea/82/5f/ea825f48a30b953a396a29a54752ff68.jpg"/>

demo

  • Related