使用图像遮罩div并设置渐变背景动画

时间:2020-07-30 03:35:00

标签: html css svg css-animations mask

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

要求:

  • 蒙版图像必须为jpg或png
  • 要屏蔽的元素最好是<div>
  • 渐变应为CSS,最好来自<div>背景

面具应该看起来像这样:

enter image description here

我放下了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动画和图像蒙版!

2 个答案:

答案 0 :(得分:2)

您可以使用CSS mask,但首先需要创建如下的PNG图片:

enter image description here

然后按如下所示使用它:

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

我使用的图像质量很差。我只关注技巧而不是质量。

答案 1 :(得分:1)

这里是完整的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}
    }