【问题标题】:Consistent filling of SVG's rectanglesSVG矩形的一致填充
【发布时间】:2019-10-11 21:45:07
【问题描述】:

如何使这些正方形中的每一个都始终从左到右填充红色;并且当一个填充红色时,前一个将具有默认颜色?

#foo > rect {
  height: 32px;
  width: 32px;
}
<svg id=foo height=32 width=160>
  <rect x=0 y=0 />
  <rect x=64 y=0 />
  <rect x=128 y=0 />
</svg>

这个动画必须是可重复的。

【问题讨论】:

    标签: javascript html css svg svg-animate


    【解决方案1】:

    如果您对 CSS 解决方案持开放态度,您可以使用背景动画模拟这种效果,您可以轻松缩放到任意数量的正方形,但不会褪色:

    .rect {
      height: 32px;
      width:calc(40px*10); /* 10 Squares*/
      background:
       /* This gradient will make the red color to fade from the first to the last*/
        linear-gradient(red,red) 0 0/32px 100% no-repeat,
        /* This gradient will create the squares (32px of black then 8px of transparent)*/
        repeating-linear-gradient(to right,black 0 32px,transparent 32px 40px);
      margin:0 5px;
      animation:change 10s steps(10) infinite;
    }
    
    @keyframes change{
      to {
        background-position:calc(100% + 32px) 0,0 0;
      }
    }
    &lt;div class="rect"&gt;&lt;/div&gt;

    使用 CSS 变量,您可以控制不同的值:

    .rect {
      --s: 32px;  /* Square size  */
      --nb: 10;   /* Square number */
      --gap: 8px; /* gap between squares */
      --c1:black;
      --c2:red;
      height: var(--s);
      width:calc((var(--gap) + var(--s))*var(--nb));
      background:
        linear-gradient(var(--c2),var(--c2)) 0 0/var(--s) 100% no-repeat,
        repeating-linear-gradient(to right,var(--c1) 0 var(--s),#fff var(--s) calc(var(--s) + var(--gap)));
      margin:5px;
      animation:change calc(var(--nb)*1s) steps(var(--nb)) infinite;
    }
    
    @keyframes change{
      to {
        background-position:calc(100% + var(--s)) 0,0 0;
      }
    }
    <div class="rect"></div>
    
    <div class="rect" style="--nb:8;--s:50px;--c1:green;--c2:yellow"></div>
    
    
    <div class="rect" style="--nb:15;--s:10px;--c2:blue"></div>

    【讨论】:

      【解决方案2】:

      使用 CSS keyframes:

      #foo > rect {
        height: 32px;
        width: 32px;
        animation: anim 3s infinite;
      }
      
      #foo > rect:nth-of-type(1){
        animation-delay: 0s;
      }
      
      #foo > rect:nth-of-type(2){
        animation-delay: 1s;
      }
      
      #foo > rect:nth-of-type(3){
        animation-delay: 2s;
      }
      
      @keyframes anim{
        0% { fill: black; }
        50% { fill: red; }
        100% { fill: black; }
      }
      <svg id=foo height=32 width=160>
        <rect x=0 y=0 />
        <rect x=64 y=0 />
        <rect x=128 y=0 />
      </svg>

      【讨论】:

      • 好的,但是如果我有 100 个方格呢?
      • 设置主动画时长为100s,设置第n个方块的动画延迟为n-1。或者你应该为此使用 JS 库。
      猜你喜欢
      • 2023-03-09
      • 2018-08-25
      • 1970-01-01
      • 2020-04-11
      • 1970-01-01
      • 2014-12-26
      • 1970-01-01
      • 1970-01-01
      • 2019-03-01
      相关资源
      最近更新 更多