效果如上圖
demo及源碼地址請點擊
一直想用svg實現一條不斷延伸的線的動畫,想如果用到Linechart裏貌似挺不錯的,探索了幾回,而且查看了別人的作法,最好的實現以下:
一, css實現
html寫入:css
<svg> <path d="M111,211C140.14745710214953,189.96123397138078,299.5732639133157,16.618280939956296,377,19S506.0032804639228,158.49444440665104,576,174.88195123150945S783.0061455541424,109.65639226791797,820,98" />
css寫入:html
svg { width: 800px; height: 800px; } path { stroke-width: 3; stroke: steelblue; fill: none; stroke-dasharray:900,900; stroke-dashoffset:900; -webkit-animation: 'draw' 5s linear alternate; } @-webkit-keyframes draw { from { stroke-dashoffset: 900; } to { stroke-dashoffset: 0; } }
Ok啦前端
二, 用d3js來實現
首先引入d3庫
其次寫下以下JS代碼:css3
var svg = d3.select("body") .append("svg") .attr("width", 500) .attr("height", 500) .append("g"); var path = svg.append("path") .style("fill", "none") .style("stroke", "#000") .style("stroke-dasharray", "1000, 1000") .attr("d", "M0,35.22131329279762Q68.79999999999998,208.6160083254511,85.99999999999999,208.61462731675533C111.79999999999998,208.61255580371167,146.19999999999996,37.44013393066172,171.99999999999997,35.20750320583997S232.2,193.72835097156664,258,193.7304224846103S318.19999999999993,32.82756488680316,343.99999999999994,35.22131329279762Q361.19999999999993,36.81714556346059,430,209.68874519124003") .transition() .duration(4000) .styleTween("stroke-dashoffset", function() { return d3.interpolateNumber(1000, 0); });
咱們想要的效果也就實現了.web
解釋一下:其實兩個實現的原理是同樣的,都是使用了一點小技巧,分別使用css3.0和D3的動畫改變svg:path的stroke-dasharray和stroke-dashoffset屬性值,其中前一屬性把path變成一條虛實相間的線,後一屬性決定這條虛實相間線的起始位置,技巧是把虛實相間的間隔設置到超過整條Path長度,以上我取了1000.segmentfault
但願個人文章能幫助到你,更多資料請翻閱d3js.org,
我是朱現明,任職於精碩科技可視化部門前端開發,更多精彩的文章即將奉上.app