首页 > 解决方案 > Matter.js — 如何防止 mouseConstraint 捕获滚动事件?

问题描述

我正在尝试启用滚动到包含 Matter.js 画布的页面。我到处看了看,建议添加removeEventListener,这样鼠标约束就不会劫持滚动事件。不幸的是,我没有成功。如何启用滚动?

先感谢您!

代码沙盒

代码

import "./styles.css";
import Matter from "matter-js";

//Fetch our canvas
var canvas = document.getElementById("world");

//Setup Matter JS
var engine = Matter.Engine.create();
var world = engine.world;
var render = Matter.Render.create({
  canvas: canvas,
  engine: engine,
  options: {
    width: 500,
    height: 500,
    background: "transparent",
    wireframes: false,
    showAngleIndicator: false
  }
});

//Add a ball
var ball = Matter.Bodies.circle(250, 250, 50, {
  density: 0.04,
  friction: 0.01,
  frictionAir: 0.00001,
  restitution: 0.8,
  render: {
    fillStyle: "#F35e66",
    strokeStyle: "black",
    lineWidth: 1
  }
});
Matter.World.add(world, ball);

//Add a floor
var floor = Matter.Bodies.rectangle(250, 520, 500, 40, {
  isStatic: true, //An immovable object
  render: {
    visible: false
  }
});
Matter.World.add(world, floor);

//Make interactive
var mouseConstraint = Matter.MouseConstraint.create(engine, {
  //Create Constraint
  element: canvas,
  constraint: {
    render: {
      visible: false
    },
    stiffness: 0.8
  }
});
Matter.World.add(world, mouseConstraint);

// Why is this not working?
mouseConstraint.mouse.element.removeEventListener(
  "mousewheel",
  mouseConstraint.mouse.mousewheel
);
mouseConstraint.mouse.element.removeEventListener(
  "DOMMouseScroll",
  mouseConstraint.mouse.mousewheel
);

//Start the engine
Matter.Engine.run(engine);
Matter.Render.run(render);

标签: javascriptmouseeventmatter.js

解决方案


这是一个 HTML 问题。在 index.html 中设置overflowscroll


推荐阅读