Search code examples
javascriptcsscss-animationscss-mask

Making a css animation using a transparent gradient mask


I am currently making an animation that will apply a gradient mask on an image. The mask is a transparent mask and it will transform from right to left of the image. Here is my code.

<!DOCTYPE html>
<html>
<head>
<style> 
.container {
 height: 100vh;
 width: 100vw;
 background-color: white;
 position: relative;
}

.first {
 background-image: url('https://i.ibb.co/17zzm7P/flower.jpg'); 
 background-size:cover;
 position: absolute;
 height: 100%;
 width: 100%;  
 -webkit-mask-image:  linear-gradient(to left, transparent 0px, black 20rem, black);
 -webkit-animation: rightToLeft 5s forwards;  
}

@keyframes rightToLeft {
 0% {
    -webkit-mask-position: 100vw 0%;
    mask-position: 100vw 0%;
    
  }
  100% {
    -webkit-mask-position:  0vw 0vw;
    mask-position: 0vw 0vw;
    
  }
}

</style>
</head>
<body>

<div class="container">
<div id="first" class="first"> </div>
</div>
</body>
</html>

Basically, the animation works well. However, the mask image is only applied to a specific area when it moves from right to left. Because the mask is transparent, I expect when it moves to the new area, the previous area it passed through is also transparent. How can I do to make the previous area transparent too?

Mask image Thank you so much for your time.


Solution

  • You are almost good, you only need to disable the repetition by using mask-repeat: no-repeat

    .container {
      height: 100vh;
      background-color: white;
      position: relative;
    }
    
    .first {
      background-image: url('https://i.ibb.co/17zzm7P/flower.jpg');
      background-size: cover;
      position: absolute;
      height: 100%;
      width: 100%;
      -webkit-mask-image: linear-gradient(to left, transparent, black 20rem);
      -webkit-mask-repeat: no-repeat;
      -webkit-animation: rightToLeft 5s forwards;
    }
    
    @keyframes rightToLeft {
      0% {
        -webkit-mask-position: 100vw 0%;
        mask-position: 100vw 0%;
      }
      100% {
        -webkit-mask-position: 0vw 0vw;
        mask-position: 0vw 0vw;
      }
    }
    
    body {
     margin:0;
    }
    <div class="container">
      <div id="first" class="first"> </div>
    </div>