【问题标题】:Dynamically changing the 'fill' level of an SVG in react在反应中动态更改 SVG 的“填充”级别
【发布时间】:2020-06-13 05:24:51
【问题描述】:

我有一个显示填充水平的 SVG 圆角容器。我需要动态更改填充水平。如果容器是矩形,这将是微不足道的,但圆角需要一条路径。

这是黑色“填充区域”的路径

`M0, 220 L100,220 L100,220 C100,231.045695 91.045695,240 80,240 L20,240 C8.954305,240 1.3527075e-15,231.045695 0,220 L0,120 L0,120 Z`

我需要知道要更改路径的哪些元素才能以干净的方式填充和清空水箱。

【问题讨论】:

    标签: reactjs svg


    【解决方案1】:

    即使您找到了装满水箱的方法,您也必须注意顶部边框。

    const { useState, useRef, useEffect } = React;
    
    const App = () => {
      const [value, setValue] = useState(220);
      const handle = useRef(null);
     
      useEffect(() => {
        if(value < 50) {
          clearTimeout(handle.current);
        }
      }, [value]);
     
      useEffect(() => {
      
        let isUnmounted = false;
      
        const loop = () => {
          
          if(isUnmounted) {
            return;
          }
          
          setValue(value => value - 10);
          
          handle.current = setTimeout(loop, 200);
        }
      
        handle.current = setTimeout(loop, 200);
        
        return () => {
          isUnmounted = true;
          clearTimeout(handle.current);
        }
      }, [])
    
    return <div>
      <svg width="400" height="400">
        <path d={`M0, ${value} L100,${value} L100,220 C100,231.045695 91.045695,240 80,240 L20,240 C8.954305,240 1.3527075e-15,231.045695 0,220 L0,120 L0,120 Z`}/>
        <rect fill="none" stroke="black" x="0" y="40" width="100" height="200" rx="15" />
      </svg>
    </div>
    }
    
    ReactDOM.render(
        <App />,
        document.getElementById('root')
      );
    svg, path {
      transition: all .3s ease-in;
    }
    <script src="https://unpkg.com/react/umd/react.development.js"></script>
    <script src="https://unpkg.com/react-dom/umd/react-dom.development.js"></script>
    <script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
    <div id="root"></div>

    【讨论】:

      【解决方案2】:

      您不需要新的形状。您可以使用线性渐变:

      <svg viewBox="0 0 100 120" width="100">
         <linearGradient id="lg" x1 = "0%" y1 = "0%" x2 = "0%" y2 = "100%">
         <stop offset="0%" stop-color="#fff"></stop>
         <stop offset="50%" stop-color="#fff"></stop>
         <stop offset="50%" stop-color="#f00"></stop>
         <stop offset="100%" stop-color="#f00"></stop>
        </linearGradient>
        <rect x="10" y="10" width="50" height="100" rx="15" ry="15" fill="url(#lg)" stroke="black" />
      </svg>

      为了动态更改填充水平,您需要将第二个和第三个停止偏移的值更改为${100 - yourvalue}%

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多