详细介绍SVG的stroke-dashoffset虚线偏移属性,学习如何控制虚线的起始位置和创建流动动画效果。通过实例掌握虚线偏移的应用技巧。 stroke-dashoffset属性用于设置虚线模式的起始偏移量,常用于创建虚线动画效果。
<element stroke-dashoffset="偏移值"/>
偏移值表示虚线模式从起点偏移的距离,正值向后偏移,负值向前偏移。
<line x1="30" y1="30" x2="270" y2="30" stroke="#3498db" stroke-width="3" stroke-dasharray="10,5" stroke-dashoffset="0"/>
<line x1="30" y1="60" x2="270" y2="60" stroke="#3498db" stroke-width="3" stroke-dasharray="10,5" stroke-dashoffset="5"/>
<line x1="30" y1="90" x2="270" y2="90" stroke="#3498db" stroke-width="3" stroke-dasharray="10,5" stroke-dashoffset="10"/>
<line x1="30" y1="120" x2="270" y2="120" stroke="#3498db" stroke-width="3" stroke-dasharray="10,5" stroke-dashoffset="15"/>
负值会让虚线向前偏移,效果与正值相反。
<line x1="30" y1="30" x2="270" y2="30" stroke="#e74c3c" stroke-width="3" stroke-dasharray="10,5" stroke-dashoffset="-5"/>
<line x1="30" y1="60" x2="270" y2="60" stroke="#e74c3c" stroke-width="3" stroke-dasharray="10,5" stroke-dashoffset="-10"/>
<line x1="30" y1="90" x2="270" y2="90" stroke="#e74c3c" stroke-width="3" stroke-dasharray="10,5" stroke-dashoffset="-15"/>
通过CSS动画改变stroke-dashoffset,可以创建虚线流动效果。
<style>
.dash-flow {
stroke-dasharray: 10,5;
animation: dash-flow 1s linear infinite;
}
@keyframes dash-flow {
to { stroke-dashoffset: -15; }
}
</style>
<line x1="30" y1="30" x2="270" y2="30" stroke="#3498db" stroke-width="3" class="dash-flow"/>
利用stroke-dasharray和stroke-dashoffset组合,可以实现路径绘制动画效果。
<style>
.draw-line {
stroke-dasharray: 300;
stroke-dashoffset: 300;
animation: draw 2s ease-in-out forwards;
}
@keyframes draw {
to { stroke-dashoffset: 0; }
}
</style>
<path d="M 30,100 Q 80,30 150,80 T 270,50" fill="none" stroke="#3498db" stroke-width="3" class="draw-line"/>
<style>
.progress-ring {
stroke-dasharray: 251.2;
stroke-dashoffset: 251.2;
animation: progress 3s ease-out forwards;
}
@keyframes progress {
to { stroke-dashoffset: 62.8; }
}
</style>
<circle cx="150" cy="75" r="40" fill="none" stroke="#ecf0f1" stroke-width="8"/>
<circle cx="150" cy="75" r="40" fill="none" stroke="#3498db" stroke-width="8" class="progress-ring" transform="rotate(-90 150 75)"/>
<style>
.loading {
stroke-dasharray: 50,200;
stroke-dashoffset: 0;
animation: loading 1.5s ease-in-out infinite;
}
@keyframes loading {
50% { stroke-dasharray: 150,50; stroke-dashoffset: -50; }
100% { stroke-dashoffset: -200; }
}
</style>
<circle cx="150" cy="60" r="35" fill="none" stroke="#3498db" stroke-width="4" class="loading" transform="rotate(-90 150 60)"/>