防止在主体上滚动(Matter.js)

时间:2019-07-23 17:03:18

标签: javascript matterjs matter.js

背景

我正在努力取得成就,但这确实使我发疯。因此,任何帮助将不胜感激!

我已经在Matter.js中创建了一个场景,该场景将放置在页面下方的容器中。我希望访客能够与场景互动,拖放尸体。但是允许交互会产生一个问题,即Matter.js会阻止用户在鼠标悬停在画布上时滚动。

要解决此问题,我正在使用以下代码:

mouseConstraint.mouse.element.removeEventListener("mousewheel", mouseConstraint.mouse.mousewheel);
mouseConstraint.mouse.element.removeEventListener("DOMMouseScroll", mouseConstraint.mouse.mousewheel);

这使用户可以滚动浏览页面,并且仍然可以通过单击和拖动主体来与场景进行交互,因为仅删除了滚动事件侦听器。至少在台式机上。

问题

但是,在移动设备上,触摸事件是使用户可以在页面上滚动的事件,因此这需要我也删除touchmovetouchstart和{{ 1}}来自Matter.js中鼠标约束的事件侦听器。像这样:

touchend

这是发生问题的地方。如果删除触摸事件,则用户可以在画布上滚动,但是无法与场景进行交互,因为这需要激活触摸事件。

所以我想知道是否有任何方法可以添加触摸事件,但只允许它们在场景中的某些物体上工作?我发现可以将mouseConstraint.mouse.element.removeEventListener('touchmove', mouseConstraint.mouse.mousemove); mouseConstraint.mouse.element.removeEventListener('touchstart', mouseConstraint.mouse.mousedown); mouseConstraint.mouse.element.removeEventListener('touchend', mouseConstraint.mouse.mouseup); 用作布尔值,以了解是否已单击/触摸了正文。可以以此为基础使用它吗?:

mouseConstraint.body

1 个答案:

答案 0 :(得分:0)

这是我想出的解决方案。这并不完美,但总比没有好。

 let touchStart;
  mouseConstraint.mouse.element.addEventListener('touchstart', (event) => {
    if (!mouseConstraint.body) {
      touchStart = event;
    }
  });

  mouseConstraint.mouse.element.addEventListener('touchend', (event) => {
    if (!mouseConstraint.body) {
      const startY = touchStart.changedTouches[0].clientY;
      const endY = event.changedTouches[0].clientY;
      const delta = Math.abs(startY - endY);

      if (delta > 80) {
        window.scrollTo(0, 600);
      }
    }
  });

您监听触摸开始事件并将其存储在一个变量中。然后在 touchend 事件中检查滑动是否足够大以构成滚动,然后滚动到内容。