Trap the user's cursor within an element for nicer game controls.
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 = documentcreateElement'cavas'var trap = require'pointer-trap'canvasvar ticker = require'ticker'60 canvasvar x = 0var y = 0// either on tick...tickeron'tick'x = trapposxy = trapposy// or on capture...trapon'data'x = posxy = posyvar ctx = canvasgetContext'2d'tickeron'draw'canvaswidth = windowinnerWidthcanvasheight = windowinnerHeightctxfillStyle = traptrapped ? '#0f0' : '#f00'ctxfillRectx - 4 y - 4 8 8