背景
我想取得一些成就,但这真的让我发疯了。因此,任何帮助都将不胜感激!
我已经在Matter.js中创建了一个场景,它将被放置在页面下面的容器中。我希望来访者能够与现场互动,拖放身体。但是,允许交互会造成这样的问题,即每当鼠标在画布上时,Matter.js就阻止用户滚动。
因此,为了解决这个问题,我使用了以下代码:
mouseConstraint.mouse.element.removeEventListener("mousewheel", mouseConstraint.mouse.mousewheel);
mouseConstraint.mouse.element.removeEventListener("DOMMouseScroll", mouseConstraint.mouse.mousewheel);这使得用户可以在页面中滚动,仍然可以通过单击和拖动主体来与场景进行交互,因为删除的只是滚动事件侦听器。至少在桌面上。
问题
但是,在移动平台上,触摸事件使用户能够在页面上滚动,因此需要我从touchmove、touchstart和touchend事件侦听器中删除Matter.js中的鼠标约束。如下所示:
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作为布尔值,以便知道是否单击/触摸了一个身体。这能在某种程度上与此作为基础吗?:
Matter.Events.on(mouseConstraint, "mousedown", function(event) {
if (mouseConstraint.body) {
console.log("Body clicked!");
}
});发布于 2021-03-25 13:42:11
这就是我想出的解决办法。这并不完美,但总比什么都没有强。
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);
}
}
});您可以侦听touch start事件并将其存储在变量中。然后,在touchend事件中,您检查一下swipe是否足够大以构成滚动,然后滚动到内容。
https://stackoverflow.com/questions/57169055
复制相似问题