Javascript (jQuery) limit mouse movement speed ins

2019-06-09 04:35发布

问题:

The task is to draw a curve ob canvas. The problem is that if mouse is moved too fast, the coordinates are skipped and not captured. (Html5/Js canvas capturing mouse coords when it moves fast - my previous post..)

Is there a cross-browser way to limit mouse speed inside an element (div, canvas, etc.)?

回答1:

I assume by "limiting mouse speed" you actually mean enable capturing high volume of mouse events so that you get more detailed information, or resolution, of the mouse path.

The browser will normally work at a high-level when it comes to mouse events. The system will capture the mouse events, but the browser will do many other tasks such as pushing events, bubbling them etc. and only capture the current mouse position when it actually can.

To compensate for this you need to use all sort of tricks such as splines.

Possible workaround

I don't intend to make a broad answer for this as it will quickly become out of scope to go through the steps and scenarios you would need for a spline approach (interpolation, knee-breaks which require relative angle tracking, smoothing etc.).

However, there is a new API called Pointer Lock API (see demo and source in that link as well) which allow the browser to work at a lower level closer to the system, so it can spawn mouse events faster and at a higher volume than it could otherwise.

It do have some drawbacks as with all low-level approaches:

  • You need to render your own cursor
  • Mouse movements are not limited to the edges so you need to provide wrapping or limits yourselves
  • It will request user for permission
  • Not supported in all browsers
  • And it target games and 3D more than drawing application

But this is the closest you will get to high volume of mouse events without interpolation etc.