clip-path 属性用于在 SVG 和 HTML 中创建复杂的裁剪区域(即剪切路径),从而只显示元素的一部分。
基本语法
selector {
clip-path: value;
}
值
clip-path 属性接受以下类型的值:
几何形状
- circle(): 定义一个圆形。
clip-path: circle(50%);
例如:clip-path: circle(50px at 50% 50%); 表示一个中心在元素中心,半径为50px的圆。
- ellipse(): 定义一个椭圆。
clip-path: ellipse(50% 50%);
例如:clip-path: ellipse(50% 25% at 50% 50%); 表示一个中心在元素中心,水平半径为元素宽度的50%,垂直半径为元素高度的25%的椭圆。
- inset(): 定义一个矩形区域,可以有圆角。
clip-path: inset(10px 20px 30px 40px);
例如:clip-path: inset(10% 20% 30% 40% round 10px); 表示一个从各边内缩指定距离并且有圆角的矩形。
- polygon(): 定义一个多边形。
clip-path: polygon(50% 0%, 100% 100%, 0% 100%);
例如:clip-path: polygon(50% 0%, 100% 50%, 50% 100%, 0% 50%); 表示一个菱形。
SVG 引用
使用定义在 SVG 内部的 元素。
clip-path: url(#clipPathId);
例如:
<svg width="0" height="0">
<defs>
<clipPath id="myClip">
<circle cx="50" cy="50" r="50" />
</clipPath>
</defs>
</svg>
<div style="clip-path: url(#myClip); width: 100px; height: 100px; background: red;"></div>
URL 引用
引用外部 SVG 文件中的 。
clip-path: url('path/to/svg#clipPathId');
示例
- 使用圆形剪切
<div style="clip-path: circle(50%); width: 200px; height: 200px; background: red;"></div>
- 使用椭圆剪切
<div style="clip-path: ellipse(50% 25% at 50% 50%); width: 200px; height: 200px; background: green;"></div>
- 使用 inset 剪切
<div style="clip-path: inset(10% 20% 30% 40% round 10px); width: 200px; height: 200px; background: blue;"></div>
- 使用多边形剪切
<div style="clip-path: polygon(50% 0%, 100% 50%, 50% 100%, 0% 50%); width: 200px; height: 200px; background: yellow;"></div>
结合动画
<div class="clip-animated"></div>
<style>
.clip-animated {
width: 200px;
height: 200px;
background: orange;
clip-path: circle(0% at 50% 50%);
animation: clip-animation 3s infinite alternate;
}
@keyframes clip-animation {
0% {
clip-path: circle(0% at 50% 50%);
}
100% {
clip-path: circle(50% at 50% 50%);
}
}
</style>