path()
Baseline 廣泛可用 *
path() CSS 函式接受一個 SVG 路徑字串,並用於 CSS 形狀和 CSS 運動路徑模組,以允許繪製形狀。path() 函式是一個 <basic-shape> 資料型別值。它可以在 CSS offset-path 和 clip-path 屬性以及 SVG d 屬性中使用。
使用 path() 函式有一些限制。路徑必須定義為單個字串,因此不能使用變數(var() 函式)建立自定義路徑。此外,路徑中的所有長度都隱含地以畫素(px)單位定義;不能使用其他單位。shape() 函式比 path() 函式提供更大的靈活性。
試一試
clip-path: path(
"M 20 240 \
L 20 80 L 160 80 \
L 160 20 L 280 100 \
L 160 180 L 160 120 \
L 60 120 L 60 240 Z"
);
clip-path: path(
"M 20 240 \
C 20 0 300 0 300 240 Z"
);
<section class="default-example" id="default-example">
<div class="transition-all" id="example-element"></div>
</section>
#default-example {
background: #ffee99;
}
#example-element {
background: linear-gradient(to bottom right, #ff5522, #0055ff);
width: 100%;
height: 100%;
}
語法
css
path("M 10 80 C 40 10, 65 10, 95 80 S 150 150, 180 80")
/* When used in clip-path only */
path(evenodd,"M 10 80 C 40 10, 65 10, 95 80 S 150 150, 180 80")
引數
<fill-rule>可選-
定義路徑的哪些部分在形狀內部。可能的值包括
-
nonzero:如果從該點繪製的射線從左到右穿過的路徑段多於從右到左穿過的路徑段,導致非零計數,則該點被視為在形狀內部。這是省略<fill-rule>時的預設值。 -
evenodd:如果從該點繪製的射線穿過奇數個路徑段,則該點被視為在形狀內部。這意味著射線每次進入形狀時,它離開的次數並不相等,這表明進入的次數為奇數,而沒有相應的退出。
警告:
<fill-rule>在offset-path中不受支援,使用它會使該屬性無效。 -
<string>-
一個包含在引號中的資料字串,用於定義一個 SVG 路徑。SVG 路徑資料字串包含路徑命令,這些命令隱式使用畫素單位。空路徑被認為是無效的。
返回值
返回一個 <basic-shape> 值。
正式語法
<path()> =
path( <'fill-rule'>? , <string> )
<fill-rule> =
nonzero |
evenodd
示例
使用 path() 函式作為 offset-path 值
在以下示例中,path() 函式被作為 offset-path 值提供,以建立球沿其移動的橢圓形路徑。
html
<div id="path">
<div id="ball"></div>
</div>
<button>animate</button>
css
#path {
margin: 40px;
width: 400px;
height: 200px;
/* draw the gray ramp */
background: radial-gradient(at 50% 0%, transparent 70%, grey 70%, grey 100%);
}
#ball {
width: 30px;
height: 30px;
background-color: red;
border-radius: 50%;
/* mark the elliptical path */
offset-path: path("M 15 15 A 6 5.5 10 0 0 385 15");
}
js
const btn = document.querySelector("button");
const ball = document.getElementById("ball");
btn.addEventListener("click", () => {
btn.setAttribute("disabled", true);
setTimeout(() => btn.removeAttribute("disabled"), 6000);
ball.animate(
// animate the offset path
{ offsetDistance: [0, "100%"] },
{
duration: 1500,
iterations: 4,
easing: "cubic-bezier(.667,0.01,.333,.99)",
direction: "alternate",
},
);
});
修改 SVG 路徑 d 屬性的值
path() 可用於修改 SVG d 屬性的值,該值在 CSS 中也可以設定為 none。
如果 d 作為 CSS 屬性受支援,則當您將滑鼠懸停在“V”符號上時,它將垂直翻轉。
CSS
css
html,
body,
svg {
height: 100%;
}
/* This path is displayed on hover */
#svg_css_ex1:hover path {
d: path("M20,80 L50,20 L80,80");
}
HTML
html
<svg id="svg_css_ex1" viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg">
<path fill="none" stroke="red" d="M20,20 L50,80 L80,20" />
</svg>
結果
規範
| 規範 |
|---|
| CSS Shapes Module Level 1 # funcdef-basic-shape-path |
瀏覽器相容性
載入中…
另見
<shape-outside>- CSS 形狀模組
- CSS 形狀概述
- SVG
path語法:帶插圖的指南,來自 CSS-tricks (2021)