【发布时间】:2020-09-06 19:59:29
【问题描述】:
我在动画中使用 Intersection Observer API 而不是滚动事件,但在尝试根据滚动位置和滚动值沿 offset-path 设置 SVG 动画时遇到了问题。
path.style.offsetDistance = element.intersectionRatio * 100 + "%";
由于 Intersection Observer 回调在每次通过 options 对象中定义的 threshold 值时都会触发,因此使用 element.intersectionRatio 为 offset-distance 设置动画会给我一个错误的动画,它只会每 25% 的滚动百分比触发一次。我可以将选项对象中的每 1% 作为阈值,如下所示:
let options = {
root: null,
rootMargin: "20px",
threshold: [0.01, 0.02, 0.03, 0.04, .....]
};
但是有更好的解决方案还是我应该切换到旧的滚动事件并在公式中使用 scrollY 值来平滑地计算每个滚动/像素的偏移距离?
其余代码:
let options = {
root: null,
rootMargin: "20px",
threshold: [0, 0.25, 0.5, 0.75, 1]
};
let callback = (entries, observer) => {
entries.forEach(element => {
if (element.isIntersecting) {
element.target.querySelectorAll("path").forEach(path => {
path.setAttribute("style", "offset-path: path('M" + generateRandomAnimationPathM() +" " + generateRandomAnimationPathM() + " L " + generateRandomAnimationPathLine() + " " + generateRandomAnimationPathLine() + "')", "offset-rotate: 0deg");
path.style.offsetDistance = element.intersectionRatio * 100 + "%";
});
}
});
}
let generateRandomAnimationPathM = () => {
return Math.floor(Math.random() * Math.floor(100));
}
let generateRandomAnimationPathLine = () => {
return Math.floor(Math.random() * Math.floor(200));
}
let observer = new IntersectionObserver(callback, options);
document.querySelectorAll('section').forEach(section => {
console.log(section)
observer.observe(section);
});
【问题讨论】:
标签: javascript svg intersection-observer