如何解决如何在页面上的特定滚动位置启动功能?
我正在尝试以下代码,其中图像在画布中翻转。
如果我放画布,比如说在页面的中间,我想知道是否存在一种方法,只有当观众进入页面的特定部分时,图像才能翻转通过。
现在,从外观上看,当您向下滚动时,图像立即开始在页面顶部右移。到您到达实际画布所在页面的中间时,图像已经完成翻转,并在最后一帧停止。
我假设我必须将功能设置为仅在用户滚动到Y轴上特定数量的像素后才触发?最好的方法是什么?
请参见下面的代码。
谢谢!
var images = new Array();
var currentLocation = 0;
var totalImages = 200;
for (var i = 1; i < totalImages; i++) {
var img = new Image;
var slug = '000' + i;
img.src = 'https://s3.amazonaws.com/clearmotion/hero/high-min/frame' + slug.slice(-3) + '-low.jpg'
images.push(img);
}
var c = document.getElementById("background");
var ctx = c.getContext("2d");
var mouseWheel = function() {
var newLocation = null;
window.addEventListener('wheel',function(e) {
e.preventDefault(); // No scroll
// update our variable at high frequency
var delta = Math.max(-1,Math.min(1,e.deltaY));
if (delta == -1) currentLocation += 1;
if (delta == 1) currentLocation -= 1;
if (currentLocation < 0) currentLocation = 0;
if (currentLocation >= (totalImages - 1)) currentLocation = (totalImages - 1);
if (newLocation === null) { // if set,we already are waiting to draw
requestAnimationFrame(setImage);
}
newLocation = currentLocation;
});
function setImage() {
if (images[newLocation]) {
ctx.fillRect(0,c.width,c.height);
ctx.drawImage(images[newLocation],1000,1000);
}
newLocation = null; // so the throttler knows we can draw again
}
}
images[0].onload = function() {
ctx.fillRect(0,c.height);
ctx.drawImage(images[currentLocation],1000);
mouseWheel();
};
<canvas id="background" width="1000" height="1000"></canvas>
解决方法
使用 The Intersection Observer API
,实际上,观看者一旦进入页面的特定部分,便可以开始翻转图像。因此,您必须检测元素在视口中的位置,在这种情况下是画布。
要执行此操作,您有多种方法。
通过使用Observer API
const element = document.querySelector("#background")
const Ob = new IntersectionObserver((entries) => {
if (entries[0].intersectionRatio <= 0) {
// Not in the viewport
} else {
// In the viewport
// You're code here
}
});
Ob.observe(element);
或者如果您想自己做。
您可以使用它,并在需要时对其进行修改
function elementInViewport(el) {
var top = el.offsetTop
var height = el.offsetHeight;
while(el.offsetParent) {
el = el.offsetParent;
top += el.offsetTop;
}
return (
top >= window.pageYOffset &&
(top + height) <= (window.pageYOffset + window.innerHeight)
);
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。