Inertial Mouse
Inertial Mouse for TypeScript
- Wraps native MouseEvent and emit pseudo mousemove events with inertial smooth motion.
- Working Demo
Install
npm instasll --save @hscmap/inertial-mouse
Example (source code of the working demo)
import { InertialMouse, V2 } from "@hscmap/inertial-mouse"
window.addEventListener('load', e => {
const sandbox = document.querySelector('.sandbox') as HTMLElement
const cursor = document.querySelector('.cursor') as HTMLElement
const dxText = document.querySelector('[name="dx"]') as HTMLInputElement
const dyText = document.querySelector('[name="dy"]') as HTMLInputElement
function setCursorPosition(r: V2) {
cursor.style.left = `${r.x}px`
cursor.style.top = `${r.y}px`
}
const im = new InertialMouse(sandbox, {
down: (e) => {
setCursorPosition(e.r)
cursor.classList.add('pressed')
},
up: () => {
cursor.classList.remove('pressed')
},
move: (e) => {
setCursorPosition(e.r)
dxText.value = `${e.d.x}`
dyText.value = `${e.d.y}`
},
movestart: () => cursor.classList.add('moving'),
moveend: () => cursor.classList.remove('moving'),
})
document.addEventListener('keydown', e => im.stop())
document.addEventListener('change', e => {
const target = e.target as HTMLInputElement
if (target.matches('[name="slick"]'))
im.physics.slick = target.checked
if (target.matches('[name="friction"]'))
im.physics.friction = Number(target.value)
if (target.matches('[name="k"]'))
im.physics.k = Number(target.value)
})
})
document.addEventListener('selectstart', e => e.preventDefault())