用CSS可以寫出漂亮的動畫。直接上例子。
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>SVG動畫</title> <style> .button{ width: 200px; height:50px; background: #fff; margin:300px auto; position: relative; border:1px solid #ddd; cursor: pointer; } .hover-text{ position: absolute; top:50%; left:50%; transform: translate(-50%, -50%); z-index: 999; } .shape{ fill:#fff; width: 200px; height: 50px; } .button:hover .shape{ fill:#fff; -webkit-animation: draw 0.5s linear forwards; animation: draw 0.5s linear forwards; } @keyframes draw { 0% { stroke-dasharray: 160 520; stroke-dashoffset: -460; stroke-width: 4px; } 100% { stroke-dasharray: 760; stroke-dashoffset: 0; stroke-width: 4px; stroke: red; } } </style> </head> <body> <div class="button"> <svg viewBox="0 0 200 50" version="1.1" xmlns="http://www.w3.org/2000/svg" > <rect class="shape"></rect> </svg> <div class="hover-text">文字標題</div> </div> </body> </html>
SVG 線條動畫基礎(chǔ)入門知識
button垂直水平居中、shape透明填充,邊框?qū)挾?px,邊框顏色#1199ff。
也許你會對fill、stroke-width等屬性有點懵,下面看看他們的描述:
fill:類比 css 中的 background-color,給 svg 圖形填充顏色;
stroke-width:類比 css 中的 border-width,給 svg 圖形設(shè)定邊框?qū)挾龋?/p>
stroke:類比 css 中的 border-color,給 svg 圖形設(shè)定邊框顏色;
stroke-linejoin | stroke-linecap:設(shè)定線段連接處的樣式;
stroke-dasharray:值是一組數(shù)組,沒數(shù)量上限,每個數(shù)字交替表示劃線與間隔的寬度;
stroke-dashoffset:則是劃線與間隔的偏移量
重點能夠?qū)崿F(xiàn)線條動畫的關(guān)鍵屬性 stroke-dasharray 。屬性 stroke-dasharray 可控制用來描邊的點劃線的圖案范式。