用图像和动画渐变背景遮盖 div

Masking a div with an image and animating gradient background

我目前正在设计一个具有动画渐变背景的徽标。

要求:

面具应该是这样的:

我有 CSS 动画,但是当涉及到从 <div> 中切割出一个形状时 我好像卡住了 jpg 或 png 图片。

我想到了什么:

我不喜欢我当前的解决方案,因为它依赖于 SVG 动画并且我屏蔽了 SVG <rect> 元素而不是 <div>。如果主要使用 CSS 实现,那么它的灵活性要差得多。但是,它完成了工作。

<!-- image masked gradient -->
<svg  height="200px" width="200px">  
    <defs>  
        <!-- the gradient for the rectangle element-->
        <linearGradient id='gradient1'>
            <stop stop-color='#020024'/>
            <stop offset='.35' stop-color='#090979'/>
            <stop offset='1' stop-color='#6699ff'/>
            </linearGradient>

        <!-- the mask shape of a thunder bolt -->
        <mask id="image-mask" x="0" y="0" width="100" height="100" >  
            <image href="https://encrypted-tbn0.gstatic.com/images?q=tbn%3AANd9GcRU8cEP-xBjtmZ2ZhpNKMc0dwE7I5a-PB8RBA&usqp=CAU" height="200" width="200"/>
        </mask>  
    </defs>

    <!-- this is the gradient rectangle element to be masked -->
    <g mask="url(#image-mask)">  
        <rect class="posr " x="10" y="0"  width="500%" height="400%" fill="url(#gradient1)">
           <animate attributeName="x" values='0px;-450px;0px' dur="5s"  repeatCount="indefinite" />
        </rect>
    </g>  
</svg>

所以我基本上想要片段中显示的效果,但主要是 CSS 动画和图像遮罩!

这里是完整的 CSS 版本。 你可以随意调整它。

https://codepen.io/antoniandre/pen/qBbzXZK?editors=1100

    .bolt {
      width: 10em;
      height: 10em;
      margin: 3em auto;
      background-color: blue;
      clip-path: polygon(35% 37%, 53% 0, 81% 0, 68% 29%, 81% 29%, 67% 53%, 79% 53%, 49% 100%, 55% 67%, 38% 67%, 53% 38%);
      animation: color-cycle 4s infinite alternate;
    }
    
    @keyframes color-cycle {
      0% {background-color: blue}
      100% {background-color: black}
    }

您可以使用 CSS mask 但您需要先创建一个 PNG 图像,如下所示:

然后像下面这样使用它:

.box {
  display:inline-block;
  width:300px;
  -webkit-mask:url(https://i.ibb.co/m9fR6H1/aLOO0.png) center/cover;
          mask:url(https://i.ibb.co/m9fR6H1/aLOO0.png) center/cover;
  background:linear-gradient(to right,red,blue,green) left/300% 100% no-repeat;
  animation:change 2s linear infinite alternate;
}

/* maintain the square ratio */
.box::before {
  content:"";
  display:block;
  padding-top:100%;
}
/**/


@keyframes change {
  to {
    background-position:right;
  }
}

body {
  background:#f2f2f2;
}
<div class="box"></div>
<div class="box" style="width:150px;"></div>

我使用的图像质量很差。我只看技巧不看质量