Is it possible to animate a CSS mask-image?
Asked Answered
V

1

13

I'd like to animate the "mask-position" property of a CSS mask image. The mask-image itself is a simple gradient, and my intended behavior is that by changing the value of the mask position, I can make the background object fade in from left to right. However, is it possible to animate this property? If not, is there a workaraound?

.header-image figure {
    mask-image: url("http://thehermitcrab.org/wp-content/themes/the-hermit-theme/images/gradient-mask-straight.png");
    animation: clip-fade 3s;
}

@keyframes clip-fade {
  0% {mask-position: 100% 0%;}
  100% {mask-position: 0% 0%;}
}

The HTML:

<div class="header-image">
<figure>
<img src="https://thehermitcrab.org/wp-content/themes/the-hermit-theme/images/footer/crab-footer-chalk-logo.png"/>
</figure>
</div>
Vedanta answered 23/2, 2020 at 4:34 Comment(0)
M
21

Not sure what kind of animation you want to perform but since it's a simple gradient no need to consider an image. Simply define the gradient and then you must define the size in order to correctly animate it.

Here is a basic example

.header-image figure {
  -webkit-mask-image: linear-gradient(90deg, #0000, #fff, #0000);
          mask-image: linear-gradient(90deg, #0000, #fff, #0000);
  -webkit-mask-size: 300% 100%;
          mask-size: 300% 100%;
  animation: clip-fade 3s infinite alternate;
}

img {
  max-width: 100%;
}

@keyframes clip-fade {
  100% {
    -webkit-mask-position: right;
            mask-position: right;
  }
}

body {
  background: red;
}
<div class="header-image">
  <figure>
    <img src="https://i.sstatic.net/lkGW7.png" />
  </figure>
</div>

Gradient used in mask works the same way as used in background so here is a related question to get more details about how to deal with the calculation: Using percentage values with background-position on a linear-gradient

Mutule answered 23/2, 2020 at 8:22 Comment(1)
It's perfect, many thanks!! Yes it's much better to define the gradient without an image. I had tried that before, but with no result (because my mistake was elsewhere) so I was just groping in the dark. My mistake was not to have defined "mask-size". Now it works as intended.Vedanta

© 2022 - 2024 — McMap. All rights reserved.