【问题标题】:Percentage circle border CSS React [duplicate]百分比圆形边框CSS React [重复]
【发布时间】:2022-01-18 22:22:44
【问题描述】:

我尝试创建一个带有边框的圆圈,我可以在其中控制红色部分与绿色部分的比例。我正在使用 React 和样式化组件。我创造了这样的东西:

import React from "react";
import styled from "styled-components";

const Wrapper = styled.div`
  margin: 50px auto;
  width: 150px;
  height: 150px;
  background: ${({ theme }) => theme.red};
  border-radius: 50%;
`;

const Circle = styled.div``;

const MaskFull = styled.div`
  width: 150px;
  height: 150px;
  position: absolute;
  border-radius: 50%;
  clip: rect(0px, 150px, 150px, 75px);
  animation: fill ease-in-out 3s;
  transform: rotate(126deg);
`;

const Fill = styled.div`
  clip: rect(0px, 75px, 150px, 0px);
  background-color: ${({ theme }) => theme.green};
  animation: fill ease-in-out 3s;
  transform: rotate(126deg);
  width: 150px;
  height: 150px;
  position: absolute;
  border-radius: 50%;
`;

const InsideCircle = styled.div`
  width: 130px;
  height: 130px;
  border-radius: 50%;
  background: #fff;
  line-height: 130px;
  text-align: center;
  margin-top: 10px;
  margin-left: 10px;
  position: absolute;
  z-index: 100;
  font-weight: 700;
  font-size: 2em;
`;

const SecondMask = styled.div`
  width: 150px;
  height: 150px;
  position: absolute;
  border-radius: 50%;
  clip: rect(0px, 150px, 150px, 75px);
`;

const Avatar: React.FC = () => {
  return (
    <Wrapper>
      <Circle>
        <MaskFull>
          <Fill />
        </MaskFull>
        <SecondMask>
          <Fill />
        </SecondMask>
        <InsideCircle />
      </Circle>
    </Wrapper>
  );
};

export default Avatar;

但正如你在图片上看到的,有一个丑陋的 1px 突出的红色片段。我在我的代码中找不到错误,我该如何修复它?

【问题讨论】:

  • 我认为这里的主要问题是border-radius 属性。尝试调整所有4个值:border-radius:topleft、topright、bottomright、bottomleft,以实现可见圆溢出的重叠。或其他解决方案,您可以创建一个带有孔的外部白色蒙版 div,以将圆圈放入其中。
  • 坦白使用 SVG,更简单

标签: javascript html css reactjs


【解决方案1】:

不认为这是您代码中的特别错误 - 只是系统正在尝试解决如何在每个 CSS 像素使用多个屏幕像素的屏幕上显示部分 CSS 像素。有些人可能会被“甩在后面”。

创建所需效果的另一种方法是使用由锥形渐变和径向渐变组成的背景图像(在中间形成“洞”)。

这是一个简单的 sn-p 来演示 HTML/CSS 中的想法。 CSS 变量 --ratio 可以在 JS 中使用 setProperty 设置为所需的红绿比例。

.ratio {
  --ratio: 0.3;
  height: 150px;
  width: 150px;
  border-radius: 50%;
  position: relative;
  clip-path: circle(50%);
}

.ratio::before {
  content: '';
  position: absolute;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
  background-image: conic-gradient(red 0 calc(var(--ratio) * 360deg), lime calc(var(--ratio) * 360deg) 360deg);
  z-index: -2;
}

.ratio::after {
  content: '';
  position: absolute;
  width: 80%;
  height: 80%;
  top: 10%;
  left: 10%;
  background-color: white;
  border-radius: 50%;
  z-index: -1;
}
&lt;div class="ratio"&gt;&lt;/div&gt;

注意:虽然可以使用更简单的设置获得相同的效果 - 实际 div 上只有一个 background-image 语句,首先是径向渐变,然后是圆锥渐变,但您可能会遇到另一个“像素”问题,曲线周围的一种模糊感。因此,这个 sn-p 用 clip-path 整理圆圈以提供平滑的边缘。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-05-22
    • 2014-02-25
    • 1970-01-01
    • 2012-09-05
    • 1970-01-01
    • 1970-01-01
    • 2023-04-04
    相关资源
    最近更新 更多