I want to build a website that allows users to map their trackpad input directly to an SVG element on the screen. On this website, we can turn on a mode: Touching a point on the trackpad should move the pointer to the corresponding point on the SVG. For example, touching the top-left corner of the trackpad would move the pointer to the top-left corner of the SVG.
This is similar to using the trackpad as a tablet. However, I cannot figure out how to access absolute trackpad coordinates from the browser. There is an old post about it but without any solution. There are also other similar questions, but they are for applications rather than website.
Ideally, I’d like this to work cross-platform via a website. Is it possible to get the absolute position on the trackpad in the browser?
First, for security reasons, modern browsers don't expose standard, widely used APIs for getting the exact trackpad coordinates. Even if the OS does have access to absolute touchpad coords, the browser intentionally does not expose these to JavaScript.
Secondly, trackpads are very different from touchscreens: trackpads typically generate relative movement (delta X/Y). Think about how a mouse works: you don't have the absolute position of the mouse on somebody's desk. Touchscreens (and tablets) give you absolute coordinates, which is what you want, because they have defined boundaries on the screen.
PointerEvent
and TouchEvent
APIs work with touchscreens or styluses—not trackpads. The solutions that do exist are complicated and far from plug and play.
You could try to simulate a virtual absolute coordinate system by tracking deltas and building up a position manually, with a little prompt at the start "Please center your finger on the trackpad" or similar, but that's hacky and I don't recommend it. Do what you wish with the code below.
let virtualX = 0, virtualY = 0;
document.addEventListener('mousemove', e => {
virtualX += e.movementX;
virtualY += e.movementY;
// map to svg
});
Won’t give you initial location (no "touch origin") without extra work
Doesn't know if user lifts their finger or not
Falls apart if the mouse moves another way (for example, an external mouse)