[英]How can I get the Intersection Observer callback trigger at every pixel when the element is intersecting?
[英]Is it possible to trigger Intersection Observer callback every scroll/pixel?
我正在为我的动画使用 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);
});
值得注意的是,您使用阈值技巧提出的建议是一种 hack,并不能保证 100% 的时间都有效。
这是因为 IntersectionObserver API 在内部使用 window.requestIdleCallback ,它只会在浏览器有时间并且用户没有与之交互时才请求浏览器执行回调。 这意味着即使在每 0.01 步设置阈值之后,动画仍然可能会出现故障,因为某些步骤可能会被跳过。
正如您已经说过的,通过使用 window.scrollY 计算元素在 scrollEvents 上的交集比,您可以轻松实现您想要实现的目标。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.