【发布时间】:2015-11-23 16:27:49
【问题描述】:
我正在尝试使用this tutorial 来实现this effect,以动态地将集合中的图像添加到画布中,以便在您滚动经过画布时呈现动画外观。页面从上到下共有三个div:div_1为整页静态图片,div_2为画布,div_3为整页静态图片。滚动过去 div_1 后,所需的行为是:
- 一旦 div_1 不在视野范围内,鼠标/触控板的滚动动作将停止向下滚动页面
- 暂停 div_2/canvas
- 鼠标/触控板将开始循环浏览集合中的所有图像(通过画布显示),直到显示最后一张图像
- 滚动动作将继续向下继续页面到 div_3。
我不知道如何启用/禁用我正在绑定的 mouseWheel 事件;从页面的最顶部开始,它(可以理解)与循环图像相关联,但我无法找到一种方法来触发它,一旦 div_1 不在视野范围内,然后在基于滚动的动画完成后解除它。
非常感谢任何帮助。
html.erb
<body>
<div class="div_1">
<!-- Full screen image to scroll past -->
</div>
<div class="div_2">
<canvas id="background" width="1280" height="720"></canvas>
</div>
<div class="div_3">
<!-- Full screen image to scroll to once animation is complete -->
</div>
</body>
Javascript
var totalImages = IMAGE_URLS.length;
var images = new Array();
for(var i = 0; i < totalImages; i++) {
var img = new Image;
img.src = IMAGE_URLS[i];
images.push(img);
}
var currentLocation = 0;
var canv;
var context;
$(document).ready(function(){
canv = document.getElementById('background');
context = canv.getContext('2d');
mouseWheel();
// See above for where this gets called
});
var mouseWheel = function() {
window.addEventListener('mousewheel', function(e) {
e.preventDefault(); // No scroll
// The following equation will return either a 1 for scroll down
// or -1 for a scroll up
var delta = Math.max(-1, Math.min(1, e.wheelDelta));
// This code mostly keeps us from going too far in either direction
if(delta == -1) currentLocation += .5;
if(delta == 1) currentLocation -= .5`;
if(currentLocation < 0) currentLocation = 0;
if(currentLocation > images.length)
currentLocation = images.length;
// See below for the details of this function
setImage(currentLocation);
});
}
var setImage = function(newLocation) {
// drawImage takes 5 arguments: image, x, y, width, height
context.drawImage(images[newLocation], 0, 0, 1280, 720);
}
【问题讨论】:
-
你所说的“参与/退出”是什么意思?您是否希望事件处理程序不再起作用?然后看看
removeEventListener。但是,如果您只是希望它在当前滚动位置为 x 时执行一个动作,如果它是 y 则执行另一个动作,那么请查看if statement -
你能不能把所有的图像都放在画布上,然后删除
div_1和div_3?如果您只想通过画布滚动浏览一组图像,则无需使用 div
标签: javascript jquery html canvas html5-canvas