SVG中有一個比較重要度屬性,stroke。stroke有很多兄弟屬性:
1)stroke:線的顏色;
2)stroke-width:線的寬度;
3)stroke-linecap:線的端點,可用值有butt、round、square、inherit;
4)stroke-dasharray:虛線描邊,可用值爲none、<dasharray>(一個逗號或空格分隔的數值列表)、inherit。表示各個虛線端的長度。可以是固定的長度值,也可以是百分比值;inherit表繼承;
5)stroke-dashoffset:虛線的起始偏移,可選值爲:<percentage>, <length>, inherit. 百分比值,長度值,繼承。
6)stroke-opacity:線的透明度。
此次主要介紹stroke-dasharray和dash-offset兩個屬性。
Html:
<svg height="100" width="100" xmlns="http://www.w3.org/2000/svg">
<line id="line" x1='0' y1='40' x2='70' y2='40'>
</svg>
Css:
#line{
stroke: black;
stroke-dasharray: 100;
stroke-dashoffset: 0;
}
此時能看到一條完整的線:若將stroke-offset設置爲99,則整條線向左平移99個像素,
此時只能看到左右一個像素點,右邊則爲虛線部分,若將dash-offset設置爲100,則只能看到虛線的部分,實線部分完全左移被遮擋。
此時,如果設置animation改變dash-offset的值就能實現黑色的實現向右平移的效果,達到動態描線的效果。
Css:
#line{
stroke: black;
stroke-dasharray: 100;
stroke-dashoffset: 100;
transition: dash 1s all ease;
}
@keyframes dash{
to{
stroke-dashoffset: 0;
}
}
如果想知道路徑或者線條的長度,可以藉助以下代碼:
var path = document.querySelector('path');
var length = path.getTotalLength();