On my website, I create a matter.js world where I have a bunch of draggable bodies. Any simple ideas on how to create a grab cursor when hovering over the bodies I had, failed. Without it, there is no indication that the elements are interactive. Do you know how to change the cursor in matter.js?
I've added html elements as bodies to matter.js, so I tried to force css cursor settings on them. Then I tried to change the cursor on mouseenter, then I tried to do it with matter.js mouse constraint, all with no effect
mConstraint = MouseConstraint.create(engine, {
mouse: mouse,
constraint: {
stiffness: 0.2,
render: {
visible: true,
},
},
});
World.add(world, mConstraint);
Events.on(mConstraint, "mousemove", function (event) {
var foundBodies = Query.point(bodies, event.mouse.position);
if (foundBodies.length > 0) {
console.log("foundBodies", foundBodies);
foundBodies.forEach(function (body) {
body.render.cursor = "grab";
});
}
});
MJS's renderer is mainly intended for prototyping, so your use case may be pushing the limits of the internal renderer. Depending on your broader application context, it may make sense to use a custom renderer. If you use the DOM as your renderer, CSS styling such as the cursor becomes natural. See this example.
For using the prototyping renderer, your move code should work more or less, but add:
to use the default cursor, and
to use the grabbing cursor. Since there's only one cursor, you don't need to set this on each body.
Here's a more complex example that uses "grabbing" and handles drags:
Another approach that involves a bit more lifting but might come in handy for certain use cases is to have an invisible sensor body positioned under the mouse on each frame which is used to detect interactions on movement:
This is set up such that the cursor only changes when placed on the green "player" box Using
[player]in the abovetouchingMousefunction is another way to achieve this. Either way, you might want to disable mouse interactions with other bodies so it's more consistent with the cursor.