Последовательное заполнение прямоугольников SVG - PullRequest
2 голосов
/ 25 мая 2019

Как сделать так, чтобы каждый из этих квадратов заливался красным цветом последовательно слева направо; а когда один заполнен красным, предыдущий будет иметь цвет по умолчанию?

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

2 голосов
/ 25 мая 2019

Если вы открыты для решения 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>
2 голосов
/ 25 мая 2019

Использовать 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>
...