简体   繁体   English

如何将背景图像放在圆形组件上?

[英]How can I put a background image on a circle component?

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("");background-image: url(""); . . Can I do the same with fill attribute (now it is transparent )?我可以对fill属性做同样的事情吗(现在它是transparent的)? The circle should look like on the second picture (the picture is just an example).圆圈应该看起来像第二张图片(图片只是一个例子)。 I am using React and styled-components.我正在使用 React 和样式化组件。

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>

在此处输入图像描述

在此处输入图像描述

This is how I would approach this.这就是我将如何处理这个问题。 Use a div with a conic gradient with an image on top to mask it.使用带有锥形渐变的div和顶部的图像来掩盖它。

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"/>

演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM