If you've ever played a windowed game, and the pointer isn't locked within the screen, you may occasionally click outside the window by mistake. This is super annoying if it happens in a tight spot, so here's a drop-in fix for the problem.
npm install pointer-trap
Returns a readable stream, which emits the current position of the mouse
(relative to the
element you've attached it to). The user can click on the
element to enable pointer lock - when not trapped, the stream will fall back to
the data it can get from the element's
Emitted periodically, passing
stream.pos to the callback.
Called each time the pointer is trapped.
Called when each time the pointer is released.
The current position of the mouse, as of the last update. If you're using a game loop, you'll get better results reading it directly this way.
A boolean value, set to true when the pointer is trapped.
var canvas = documentvar trap = canvasvar ticker = 60 canvasvar x = 0var y = 0// either on tick...ticker// or on capture...trapvar ctx = canvasticker