在上一个教程中,我们使用SVG和CSS制作了文字遮罩效果。在这个教程中,我们将要使用SVG和CSS3来向你展示两种动态遮罩文字背景的效果。第一中效果是在鼠标滑过遮罩文字的时候,文字背景会有彩虹背景动画。第二种效果是遮罩文字背景持续的动态变化,就像Disco里面的灯光在闪动。
制作这些动态遮罩文字背景的思路非常简单:创建一个有动态背景的div,我们将会使用CSS3来绘制背景并给它应用一个CSS3 animation 或 transition。然后,在div中放置SVG元素来作为文字的遮罩。
这样,最终效果是只有在文字里面的动态背景被显示出来,文字之外的部分则会被隐藏。
鼠标滑过遮罩文字背景动画效果
第一种效果的最终效果如下,用鼠标放上去看看:
HTML结构
<div id="bkDiv">
<svg width="100%" height="100%">
<defs>
<mask id="theMask">
<rect width="100%" height="100%" fill="#fff" />
<text x="5" y="65" id="theText" fill="#000">Welcome to Codicode</text>
</mask>
</defs>
<rect width="100%" height="100%" mask="url(#theMask)" fill="#fff" />
</svg>
</div>
CSS样式
body
{
background-color:#fff;
}
#bkDiv
{
// The rainbow Css3 pattern
background: linear-gradient(0deg, transparent 0%, #31009c 10%, #000084 25%,#009cff 37%,#00bd00 50%,#fff700 62%,#ff6331 75%,#de0000 90%,transparent 100%);
background-color: #333;
background-size: 10px 125px;
background-repeat : repeat;
height : 100px;
width : 620px;
background-position:center -65px;
transition: background-position 1s;
}
#bkDiv:hover
{
// on Hover the background translates 65px down
background-position:center 0px;
}
#theText
{
font-family:Impact, Charcoal, sans-serif;
font-size:65px;
stroke:#000;
stroke-width:3px;
fill-opacity:0.5;
}
当作为背景的div被鼠标滑过时,CSS3背景将产生过渡动画效果。当鼠标滑出时,背景的原点位置将回到原来的位置上。这里设置过渡动画的时间为1秒钟。
另外,文字有50%的透明度和3像素的描边,使文字看起来更加好看。
遮罩文字背景持续动画效果
先来看一下第二种Disco效果的遮罩文字背景动画效果:
第二个遮罩文字背景动画效果的HTML代码和第一个例子是一样的:
HTML结构
<div id="bkDiv">
<svg width="100%" height="100%">
<defs>
<mask id="theMask">
<rect width="100%" height="100%" fill="#fff" />
<text x="5" y="65" id="theText" fill="#000">Welcome to Codicode</text>
</mask>
</defs>
<rect width="100%" height="100%" mask="url(#theMask)" fill="#fff" />
</svg>
</div>
CSS样式
body
{
background-color:#fff;
}
#bkDiv
{
// Red dots Css3 pattern
background: linear-gradient(-45deg, #036 30%,transparent 45%,transparent 55%,#036 70%),
linear-gradient(45deg, #036 30%,transparent 45%,transparent 55%,#036 70%);
background-color: #f00;
background-size: 15px 15px;
background-position:0px 0px;
height:150px;
width:550px;
// Animating red dots (infinite loop)
animation: cAnim 1s linear 0s infinite;
}
@keyframes cAnim
{
100% {background-position:15px 0px;}
}
#theText
{
font-family:Impact, Charcoal, sans-serif;
font-size:120px;
stroke:#000;
stroke-width:5px;
fill-opacity:0.1;
stroke-opacity:1;
// Strobe light effect animation
animation: cAnim1 0.5s linear 0s infinite;
}
@keyframes cAnim1
{
100% {fill-opacity:0.9;stroke-opacity:0.5;}
}
在第二个例子中同时执行了两种动画,第一个动画是在背景上移动小圆点,第二个动画是在SVG文字的边框执行闪动效果。
SVG (Scalable Vector Graphics)是由W3C(World Wide Web Consortium)开发的一个开放的HTML标准技术。使用SVG可以制作出许多令人惊叹的动画效果,它被所有的现代浏览器所支持,包括IE9。希望你在你的下一个WEB项目中能够使用上SVG技术!