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

1.前言

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

2.属性作用

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

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. ** 意思就是单数值代表实线的长度,双数值代表虚线的长度

例子

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

stroke-dasharray: 0;

stroke-dasharray: 0;
复制代码

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

troke-dasharray: 20;

扫描二维码关注公众号,回复: 5588465 查看本文章
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官方文档

猜你喜欢

转载自juejin.im/post/5c8db3175188257e252a49da