SVG:理解stroke-dasharray和stroke-dashoffset属性

1.前言

最近刚学习SVG看到一个霓虹灯的动画效果感受很炫酷,便按照文章巧了下来,虽然实现了可是对于 stroke-dasharray和stroke-dashoffset属性还不是特别清楚,经过查找资料和看文档终于理解,但愿对你们有帮助html

2.属性做用

咱们知道SVG是在画画,那么stroke属性系列就是画笔。 stroke-dasharraystroke-dashoffset是stroke的两个属性segmentfault

stroke-dasharray

定义

官方文档给出的解释是:The stroke-dasharray property controls the pattern of dashes and gaps used to form the shape of a path's stroke. 按照个人理解:stroke-dasharray就是控制画笔的虚实,经过实线和虚线的来控制画数组

做用范围

能够在shape(形状)和text content elements(字体元素)上起做用闭包

参数

接下来重点讲下他的参数,这里是多是你们最没法理解的地方。dasharray顾名思义就是线段的数组,他的参数能够是一个数组,每一个参数又有什么含义呢 官方文档解释: **The first value and every second value in the list after it specifies the length of a dash, and every other value specifies the length of a gap between the dashes. ** 意思就是单数值表明实线的长度,双数值表明虚线的长度svg

例子

下图中每一个大方格边长是100px,线段的初始长度是200pxwordpress

stroke-dasharray: 0;

stroke-dasharray: 0;
复制代码

此时stroke-dasharray不起做用,注:当他的参数<=0时该属性将失效学习

troke-dasharray: 20;

stroke-dasharray: 20;
复制代码

能够看出来实线的长度确实是20px,为何会有虚线也是20呢,这里官方文档给出的解释是:If the list has an odd number of values, then it is repeated to yield an even number of values. 也就是说若是参数个数是单数是默认会复制一份参数,好比1 2 3 将会变成1 2 3 1 2 3六个参数测试

troke-dasharray: 120;

troke-dasharray: 120;
复制代码

按理来讲在一个参数的状况下虚线和实线应该是等长的这里不等长,很好理解描绘的是线段,超出部分将会隐藏。可是若是是个封闭图形,结果也是相同的 字体

圆

这里是一个参数的多个参数也同样的,本质上就是根据实线和虚线的长度依次描绘,这里就不测试了。动画

另外他的参数还能够是百分比,这样就不须要知道总长就能精确使用了,若是要知道总长能够使用js获取Path元素的pathLength属性

var path = document.querySelector('path');
var length = path.getTotalLength();
复制代码

stroke-dashoffset

理解了stroke-dasharray那么理解stroke-dashoffset就简单了

定义

官方文档:The stroke-dashoffset property specifies the distance into the repeated dash pattern to start the stroke dashing at the beginning of the path. If the value is negative, then the effect is the same as dash offset d: 意思就是:相对于绘制的起点偏移的量,正值(向右或者顺时针偏移),负值(向左或者逆时针)

偏移量计算公式:

d = s - | 'stroke-dashoffset' | mod s
d:偏移量  s:线段总长度  'stroke-dashoffset':参数值
复制代码

从公式咱们能够看出偏移量是一个区间的值,不管参数值多大,偏移量不会大于线段总长度

做用范围

和上面同样能够在shape(形状)和text content elements(字体元素)上起做用 而且可支持动画,从而实现炫酷的效果

参数

另外因为咱们实际设置stroke-dashoffset参数的时候不会大于线段长度,用上面的公式计算未免麻烦,咱们能够逆向理解,偏移量就是正值(向左或者逆时针)/负值(向右或者顺时针)偏移stroke-dashoffset参数的大小。

例子

stroke-dashoffset: 0;

stroke-dasharray: 120;
stroke-dashoffset: 0;
复制代码

上面为初始状态,参数为0,没偏移

stroke-dashoffset: 20;

stroke-dasharray: 120;
stroke-dashoffset: 20;
复制代码

当参数为20若是按照官方文档的理解就是:d = 200 - 20 mod 200 = 180 向右偏移了180px 而从图中明显能够看到线段往左移动了20px,因此咱们能够理解为想左偏移了参数值,封闭图形是逆时针,你们本身能够去试试。负值同理以下图

stroke-dashoffset: -20;

stroke-dasharray: 120;
stroke-dashoffset: -20;
复制代码

总结

到这里咱们基本就理解了stroke-dasharray和stroke-dashoffset这两个属性的做用和参数的意义,因为stroke-dashoffset是闭包循环的,咱们就能够使用动画效果作出炫酷的SVG效果如: 霓虹灯字体

第一次在掘金写文章,排版问题多多见谅!

参考资料

张鑫旭-鑫空间 W3官方文档

相关文章
相关标签/搜索