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

Framer Motion maskSize动画在移动端失效问题求助

SVG蒙版滚动效果移动端失效排查与解决

问题描述

使用Framer Motion实现的SVG蒙版滚动效果在PC端运行正常,但移动端蒙版尺寸无法随滚动增大,多款手机测试均出现相同问题。

代码实现

App.js

import "./styles.css";
import { useScroll, useTransform, motion } from "framer-motion";
import { useRef } from "react";

export default function App() {
  const scene = useRef(null);

  const { scrollYProgress } = useScroll({
    target: scene,
    offset: ["start start", "end end"],
  });

  const imageScale = useTransform(scrollYProgress, [0, 1], ["300px", "3000px"]);

  return (
    <>
      <div style={{ height: "30vh" }}></div>

      <h1>Look at Masking using svg</h1>

      <div className="main" ref={scene}>
        <motion.div className="mask" style={{ maskSize: imageScale }}>
          <img src="/cement-industry.jpg" />
        </motion.div>
      </div>

      <div style={{ height: "100vh" }}></div>
    </>
  );
}

styles.css

.main {
  height: 250vh;
}

.mask {
  position: sticky;
  top: 0px;
  height: 100vh;
  overflow: hidden;
  -webkit-mask-image: url(/mask-star.svg);
  mask-image: url(/mask-star.svg);
  -webkit-mask-repeat: no-repeat;
  mask-repeat: no-repeat;
  -webkit-mask-position: center center;
  mask-position: center center;
}

img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

异常截图

移动端蒙版效果异常截图

解决方案思路

  • 补全兼容性前缀:移动端WebKit内核浏览器对标准mask-size支持不完善,需同步设置-webkit-mask-size属性,修改motion.div的style:
    style={{ 
      maskSize: imageScale,
      WebkitMaskSize: imageScale
    }}
    
  • 调整单位适配:将固定像素单位替换为视窗单位(如vw),比如把["300px", "3000px"]改为["30vw", "200vw"],适配不同移动端屏幕尺寸。
  • 优化滚动监听精度:移动端滚动事件触发机制与PC端有差异,可调整useScroll的offset参数(如["start 10%", "end 10%"]),确保scrollYProgress在移动端能正确更新。
  • 检查SVG蒙版属性:确认SVG文件是否包含正确的viewBox属性,缺失该属性会导致移动端无法正常缩放蒙版图形。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 15:15:18