CSS 的 clip-path 屬性是 clip 屬性的升級版,它們的做用都是對元素進行 「剪裁」,不一樣的是 clip
只能做用於 position
爲 absolute
和 fixed
的元素且剪裁區域只能是正方形,而 clip-path
更增強大,能夠以任意形狀去裁剪元素,且對元素的定位方式沒有要求。基於這樣的特性,clip-path
經常使用於實現一些炫酷的動畫效果。css
好比:html
視差廣告效果:git
實現請參考:CodePengithub
菜單欄彈出效果:瀏覽器
實現請參考:CodePendom
clip-path
有幾大類,分別爲:svg
basic-shape
: 基本圖形,包括 inset()
、circle()
、ellipse()
、polygon()
工具
clip-source
: 經過 url()
方法引用一段 SVG 的 <clipPath>
來做爲剪裁路徑動畫
geometry-box
: 單獨使用時會將指定框的邊緣做爲剪裁路徑,或者配合 basic-shape
使用,用於定義剪裁的參考框(Reference Box)(因爲該屬性瀏覽器支持度比較低,本文暫不討論)url
inset()
用於定義一個插進的矩形,即被剪裁元素內部的一塊矩形區域。
參數類型:
inset( <shape-arg>{1,4} [round <border-radius>]? )
其中 shape-arg
分別爲矩形的上右下左頂點到被剪裁元素邊緣的距離(和margin
、padding
參數相似),border-radius
爲可選參數,用於定義 border 的圓角。
DEMO:
html:
<img class="img inset" src="http://source.unsplash.com/random/1000x1000" />
複製代碼
css:
.inset {
clip-path: inset(0);
&:active {
clip-path: inset(100px 200px 10% 20% round 20px);
}
}
複製代碼
circle()
用於定義一個圓。
參數類型:
circle( [<shape-radius>]? [at <position>]? )
其中 shape-radius
爲圓形的半徑,position
爲圓心的位置。
若是 shape-radius
爲百分比,則 100% 至關於:
sqrt(width^2+height^2)/sqrt(2)
複製代碼
width
、height
分別爲被剪裁元素的寬高。
DEMO:
html:
<img class="img circle" src="http://source.unsplash.com/random/1000x1000" />
複製代碼
css:
.circle {
clip-path: circle(100px at center);
&:hover {
clip-path: circle(50% at center);
}
}
複製代碼
ellipse()
用於定義一個橢圓。
參數類型:
ellipse( [<shape-radius>{2}]? [at <position>]? )
其中 shape-radius
爲橢圓x、y軸的半徑,position
爲橢圓中心的位置。
DEMO:
html:
<h2>Ellipse (click)</h2>
<div class="img-box">
<img class="img ellipse" src="http://source.unsplash.com/random/1000x1000" />
</div>
複製代碼
css:
.ellipse {
clip-path: ellipse(200px 500px at 50% 50%);
&:active {
clip-path: ellipse(500px 500px at 50% 50%);
}
}
複製代碼
polygon()
用於定義一個多邊形。
參數類型:
polygon( [<fill-rule>,]? [<shape-arg> <shape-arg>]# )
其中 fill-rule
爲填充規則,即經過一系列點去定義多邊形的邊界。
DEMO:
html:
<img class="img polygon" src="http://source.unsplash.com/random/1000x1000" />
複製代碼
css:
.polygon {
clip-path: polygon(0% 50%, 50% 0%, 100% 50%, 50% 100%);
&:active {
transform: rotate(720deg);
clip-path: polygon(0% 0%, 100% 0%, 100% 100%, 0% 100%);
}
}
複製代碼
即經過引用一個svg的 clipPath 元素來做爲剪裁路徑。好比,使用在 <clipPath>
中定義一個圓:
html:
<svg>
<defs>
<clipPath id="svgCircle">
<circle cx="500" cy="500" r="400" />
</clipPath>
</defs>
</svg>
<img class="img svg-circle" src="http://source.unsplash.com/random/1000x1000" />
複製代碼
css:
.svg-circle {
clip-path: url("#svgCircle");
}
複製代碼
效果:
若是以爲本身去計算和繪製一個圖形太麻煩,可使用 clippy 這個在線 clip-path
繪製工具,裏面包含了大部分經常使用的圖形,也支持可視化繪製自定義圖形。
Clippy:
天天一個小技巧(Tricks by Day),量變引發質變,但願你和我一塊兒天天多學一點,讓技術有趣一點。
全部示例將會彙總到個人 tricks-by-day github 項目中,歡迎你們蒞臨指導 😊