Johannes
Johannes

Reputation: 177

HTML5 / JS: have the cursor locked in a canvas element

So im making a html5 / js RTS game. The game can be ran fullscreen. The problem now is, players with dual screen will have their cursor go out of the canvas and jump over to the 2nd screen when they move it too far. Is there a good way, to prevent that ? I know, there is this, but this seems to hide the cursor, which is obv not what i want in an RTS game. Ofc i could draw my own cursor, but the problem with this is, the cursor drawn then will depend on the framerate, which can sometimes go a bit down and so or so it will feel a lot less smooth than the "normal" cursor. So, is there a way to lock the cursor in an element without hiding it and still be moveable but just stop at the border ?

Upvotes: 1

Views: 1171

Answers (1)

markE
markE

Reputation: 105015

There is no method to restrict mouse movements by the user.

Chuckle...If it was possible you can imagine advertisers would freeze your mouse over a "purchase now" button on an ad. :-)

If it makes sense to your design, you can have your canvas element "capture the mouse events".

Capturing the mouse makes the canvas receive all mouse events even if the mouse is physically out of the canvas element. Maybe this will be useful in your design--maybe not.

https://developer.mozilla.org/en-US/docs/Web/API/Element.setCapture

Good luck with your game!

Upvotes: 1

Related Questions