SVG路径动画(3)

本文深入探讨SVG路径动画,重点解析stroke-dasharray属性如何创建虚线效果,以及stroke-dashoffset如何配合偏移虚线。特别地,文章通过实例说明了当stroke-dasharray值等于线段长度时,结合stroke-dashoffset的特殊动画效果,并展示了如何实现一个'抽风路径'动画。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

SVG路径动画(3)

stroke-dasharray

该css属性主要用于在SVG中创建各种虚线

#line1{
    stroke: black;
    stroke-width: 10px;
    stroke-dasharray: 15 7 5 5 5 7;
    /*表示:画15px长,空7px,画5px长,空5px,画5px,空7px,后面则循环此过程
    所以在画这种特殊样式的虚线时,只需要找出被循环的那部分,然后用stroke-dasharray表示即可*/
}
#line2{
    stroke: black;
    stroke-width: 10px;
    stroke-dasharray: 10;/*表示:画10px,空10px,如此循环*/
}

<svg id="svg">
    <line x1="100" y1="100" x2="300" y2="100" id="line1"></line>
    <line x1="100" y1="200" x2="300" y2="200" id="line2"></line>
</svg>

stroke-dashoffset

该css属性用于偏移虚线

注意:stroke-dasharray与stroke-dashoffset要配套使用。在无stroke-dasharray的情况下,stroke-dashoffset不起作用

先来看一个简单的例子:

#line1{
    stroke: black;
    stroke-width: 10;
    stroke-dasharray: 10;
    stroke-dashoffset: 150;
}

<svg id="svg">
    <line x1="0" y1="100" x2="300" y2="100" id="line1"></line>
</svg>

上述代码画图解释为:

这里写图片描述

上图也表现了stroke-dashoffset的原理

特殊情况

即,当stroke-dasharray的值等于线段长度时,我们用stroke-dashoffset偏移又会怎样

#line1{
    stroke: black;
    stroke-width: 10;
    stroke-dasharray: 300;
    stroke-dashoffset: 300;
}

<svg id="svg">
    <line x1="0" y1="100" x2="300" y2="100" id="line1"></line>
</svg>

通过上面给出的图片,你应该能容易的想出运行结果

这里写图片描述

通过上面的讲解,我们来实现一个‘抽风路径’的动画

#svg{
    width: 500px;
    height: 500px;
    border: 1px solid #ccc;
}
#line1{
    stroke: black;
    stroke-width: 10;
    stroke-dasharray: 300;
    animation: move 1s linear alternate infinite;
}   
@keyframes move{
    0%{
        stroke-dashoffset: 0;
    }
    100%{
        stroke-dashoffset: 300;
    }
}

<svg id="svg">
    <line x1="0" y1="100" x2="300" y2="100" id="line1"></line>
</svg>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值