如何修复HTML中沿缺角矩形SVG折线路径移动圆点的卡顿重置问题
问题原因
stroke-dashoffset动画的终点数值没有和路径总长度、stroke-dasharray的周期长度匹配,无限动画每次循环结束后无法无缝衔接,就会出现抖动、位置跳变的问题。- 你预设的路径长度和Illustrator导出的polyline实际长度不符,参数不匹配导致衔接断层。
修复方案
- 先获取路径的精确总长度:给polyline标签添加
id="movePath",然后在浏览器控制台执行以下代码即可拿到精准的路径长度值:
console.log(document.getElementById('movePath').getTotalLength())
你当前提供的polyline实测总长度约为546。
- 调整CSS动画参数,保证动画周期刚好匹配路径长度,实现无缝循环:
修改后的CSS代码如下:
.dot { filter: blur(0.3px); /* 圆点长度10,透明段长度和路径总长度一致,确保全程只有一个圆点 */ stroke-dasharray: 10 546; animation-name: dash; animation-duration: 20000ms; animation-iteration-count: infinite; animation-timing-function: linear; } @keyframes dash { from { stroke-dashoffset: 0; } to { /* 偏移总量=圆点长度+透明段长度,刚好走完一整圈回到起点,无跳变 */ stroke-dashoffset: -556; } }
修改后的HTML代码如下:
<!DOCTYPE html> <html> <head> <title>Title of the document</title> <link rel="stylesheet" href="style3.css"> </head> <body> <svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 612 792" style="enable-background:new 0 0 612 792;" xml:space="preserve"> <style type="text/css"> .st0{fill:none;stroke:#010101;stroke-width:10;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:10;} </style> <polyline id="movePath" class="st0 dot" points="353.24,507.95 387.74,507.45 387.74,283.45 223.74,283.45 224.24,445.95 "/> </svg> </body> </html>
如果后续你调整了路径形状,重新获取一次总长度,替换CSS里的对应数值即可。
内容的提问来源于stack exchange,提问作者Stapyman
相关产品推荐
相关产品推荐

