【问题标题】:How can I put a background image on a circle component?如何将背景图像放在圆形组件上?
【发布时间】:2022-01-19 20:20:24
【问题描述】:

我编写了下面的代码,它为我制作了一个带有部分红色和绿色边框的圆圈。它显示在第一张照片中。

现在我的问题是如何用图片填充里面的圆圈?我的意思是background-image: url("");。我可以对fill 属性做同样的事情吗(现在是transparent)?圆圈应该看起来像第二张图片(图片只是一个例子)。我正在使用 React 和 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>

【问题讨论】:

  • 您正在尝试做的称为图像屏蔽查看此链接以供参考:css-tricks.com/almanac/properties/m/mask-image
  • 但我在mask-image中没有什么可设置的
  • 这需要用 SVG 完成吗?您可以使用img 执行此操作,然后使用:before:after 来作为红色/绿色边框。
  • 我想设置圆圈填充绿色条的百分比,我可以通过stroke-dashoffset 来完成。如果imgbeforeafter 可能,我不需要使用svg 执行此操作。你能告诉我怎么做吗?

标签: javascript html css reactjs styled-components


【解决方案1】:

这就是我的处理方式。使用带有圆锥渐变的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"/>

【讨论】:

    猜你喜欢
    • 2013-05-08
    • 1970-01-01
    • 1970-01-01
    • 2023-03-23
    • 2017-04-28
    • 2012-07-14
    • 1970-01-01
    • 1970-01-01
    • 2021-07-12
    相关资源
    最近更新 更多