You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SVG文字动画在部分移动设备中显示异常求助

SVG文字动画在部分移动设备上显示异常的问题

我在网页中添加了SVG文字动画并部署至GitHub Pages,但部分移动设备打开时,动画显示效果与预期不符。预期为文字描边从左到右逐步绘制的完整动画,部分手机上则出现描边显示不完整、错位的情况,且问题仅出现在部分移动设备中。

实现代码

HTML

<svg viewBox="0 0 1650 400">
    <text x="50%" y="70%" fill="transparent" text-anchor="middle">
        TECHNE
    </text>
</svg>

CSS

svg text{
    font-size: 7rem;
    stroke: #0ed1c1;
    font-size: 9rem;
    font-weight: 700;
    stroke-width: 5;
    animation: textAnimate 5s infinite;
}

@keyframes textAnimate{
    0%{
        stroke-dasharray: 0 50%;
    }
    100%{
        stroke-dasharray: 50% 0;
    }
}

问题分析与修复方案

核心原因

部分移动端浏览器对CSS中stroke-dasharray的百分比单位支持存在兼容性问题,加上移动端字体渲染路径长度与桌面端的差异,导致动画计算偏差,出现显示异常。

修复方案

  1. 替换百分比单位为具体路径长度
    使用JavaScript获取文字的实际路径长度,通过CSS变量传递给动画,确保动画计算精准:

    // 获取文字元素并计算路径长度
    const svgText = document.querySelector('svg text');
    const textPathLength = svgText.getTotalLength();
    svgText.style.setProperty('--text-length', textPathLength);
    

    修改CSS动画:

    svg text{
        font-size: clamp(3rem, 8vw, 9rem); /* 响应式字体大小适配移动端 */
        stroke: #0ed1c1;
        font-weight: 700;
        stroke-width: 5;
        animation: textAnimate 5s infinite;
        font-family: 'Arial Black', sans-serif; /* 固定字体避免渲染差异 */
    }
    
    @keyframes textAnimate{
        0%{
            stroke-dasharray: 0 var(--text-length);
        }
        100%{
            stroke-dasharray: var(--text-length) 0;
        }
    }
    
  2. 优化SVG响应式布局
    为SVG添加响应式样式,避免移动端缩放导致的布局错位:

    svg {
        width: 100%;
        height: auto;
        max-width: 1650px; /* 限制最大宽度匹配viewBox */
    }
    
  3. 完善动画逻辑
    若需要循环动画的平滑过渡,可调整关键帧,让动画在结束后自然衔接:

    @keyframes textAnimate{
        0%, 100%{
            stroke-dasharray: 0 var(--text-length);
        }
        50%{
            stroke-dasharray: var(--text-length) 0;
        }
    }
    

内容的提问来源于stack exchange,提问作者Jubin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 06:20:27