可以创建一个只有元素的部分区域可以显示的剪切区域。区域内的部分显示,区域外的隐藏。
这是一个神奇的CSS属性,值可以是以下几种
剪裁成一个矩形
clip-path: inset(<距离元素上面的距离>,<距离元素右面的距离> ,<距离元素下面的距离>,<距离元素左面的距离>,<圆角边框> )
<style>
.demo{
width: 200px;
height: 100px;
background-image: url(./01.jpg);
}
.inset{
clip-path: inset(2px 2px 20px 20px round 10px);
}
</style>
<div class="demo inset"></div>
原图像:
效果:
.inset2{
clip-path: inset(10px 20px round 10px);
}
.inset2{
clip-path: inset(20px round 10px);
}
剪裁成一个圆
clip-path: circle(圆的半径 at 圆心水平位置 圆心垂直位置)
<style>
.demo{
width: 200px;
height: 100px;
background-image: url(./01.jpg);
}
.inset{
clip-path: circle(50px at 50% 50%);
}
</style>
<div class="demo inset"></div>
圆心位置也可以是一个值的合写
clip-path: circle(50% at 50%)
效果:
剪裁成一个椭圆
clip-path: ellipse(圆的水平半径 圆的垂直半径 at 圆心水平位置 圆心垂直位置)
<style>
.demo{
width: 200px;
height: 100px;
background-image: url(./01.jpg);
}
.inset{
clip-path: ellipse(80px 40px at 50% 50%);
}
</style>
<div class="demo inset"></div>
圆心位置也可以是一个值的合写
clip-path: ellipse(80px 40px at 50%);
效果:
剪裁成一个多边形,这里其实就是描点,多点连线,最少三个点,以距离左上角的长度为单位,已经支持百分比
clip-path: polygon(<距离左上角的X轴长度 距离左上角Y轴的长度>,<距离左上角的X轴长度 距离左上角Y轴的长度>,<距离左上角的X轴长度 距离左上角Y轴的长度>)
<style>
.demo{
width: 200px;
height: 100px;
background-image: url(./01.jpg);
}
.inset{
clip-path: polygon(50% 0, 0 100%, 100% 100%);
}
</style>
<div class="demo inset"></div>
效果:
polygon的可定制性极强,发挥脑力,无限可能。
比如五角星,文字形状等等。
五角星示例
clip-path:polygon(50% 0,65% 40%, 100% 40%,72% 60%,85% 100%,50% 75%,15% 100%,28% 60%,0 40%,35% 40%);
clip-path还支持url值,可以结合svg图形实现更复杂的裁剪效果
将url关联到svg图像的clipPath结节id上,具体实现看下方代码
示例代码如下:
<style>
.heart {
width: 135px;
height: 135px;
clip-path: url(#heart);
}
</style>
<svg version="1.1" xmlns="http://www.w3.org/2000/svg" width="0" height="0">
<clipPath id="heart">
<path fill="deepskyblue" d="m67.25,28.9c27.42,-69.1 134.84,0 0,88.85c-134.84,-88.85 -27.42,-157.96 0,-88.85z" />
</clipPath>
</svg>
<img src="./01.jpg" class="heart">
clip-path属性是支持animate动画的。能低成本实现各种特效。
代码如下:
.heart {
width: 135px;
height: 135px;
clip-path: circle(10% at 50%);
transition: 1s;
}
.heart:hover{
clip-path: circle(50% at 50%);
}
</style>
<img src="./01.jpg" class="heart">
与clip-path相似的属性还有个mask,目前是实验中特性。这个后面专门再写文章记录。