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
相关产品推荐
相关产品推荐

