【发布时间】:2021-01-13 02:57:39
【问题描述】:
我正在尝试使用以下代码在画布中翻转图像。
如果我把画布放在页面的中间,我想知道是否有办法只在查看者到达页面的特定部分时才让图像翻阅。
现在,从外观上看,图像在页面顶部开始翻转,当您向下滚动时立即开始。当您到达实际画布所在的页面中间时,图像已经完成翻转,并且在最后一帧停止。
我假设我必须将功能设置为仅在用户滚动到 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, 0, c.width, c.height);
ctx.drawImage(images[newLocation], 0, 0, 1000, 1000);
}
newLocation = null; // so the throttler knows we can draw again
}
}
images[0].onload = function() {
ctx.fillRect(0, 0, c.width, c.height);
ctx.drawImage(images[currentLocation], 0, 0, 1000, 1000);
mouseWheel();
};
<canvas id="background" width="1000" height="1000"></canvas>
【问题讨论】:
-
您可以使用
onscrol事件并使用window.scrollY来获取滚动了多少 -
具体我该怎么做?有没有办法在我的 HTML 中的@AksJacoves 这不是 onscroll -> onscroll更正,事件是
onscroll而不是onscroll。您可以将此事件添加到文档中,例如:document.addEventListener ('onscroll', function ... '),每当您在页面上听到滚动时,都会调用该函数。在其中您检查从顶部到用户所在位置的距离,并检查从元素到顶部的距离是否相同
标签: javascript html jquery canvas html5-canvas