Monsieur Pierre Doune
Monsieur Pierre Doune

Reputation: 747

Consistent filling of SVG's rectangles

How to make each of these squares filled with red colour consistently left to right; and when one filled with red, previous will have default colour?

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

This animation must be repeatable.

Upvotes: 2

Views: 56

Answers (2)

Temani Afif
Temani Afif

Reputation: 273990

If you are open to a CSS solution you can simulate such effect using background animation where you can easily scale to any number of square but without fading:

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

With CSS variable you can control the different values:

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

Upvotes: 3

Anurag Srivastava
Anurag Srivastava

Reputation: 14423

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

Upvotes: 2

Related Questions