一致地填充SVG的矩形

时间:2019-05-25 17:13:23

标签: javascript html css svg svg-animate

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

#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>

此动画必须是可重复的。

2 个答案:

答案 0 :(得分:1)

使用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>

答案 1 :(得分: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;
  }
}
<div class="rect"></div>

使用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>