Skip to content

Commit

Permalink
Update DOM.mousePos() with Leaflet code
Browse files Browse the repository at this point in the history
This **partially** fixes maplibre#1160, by using an adaptation of Leaflet's
`L.DOMEvent.getMousePosition()`.

The `DOM.touchPos()` static method should still display the bug.

Signed-off-by: Iván Sánchez Ortega <[email protected]>
  • Loading branch information
IvanSanchez committed Mar 15, 2023
1 parent cecde6a commit 17f5572
Showing 1 changed file with 24 additions and 4 deletions.
28 changes: 24 additions & 4 deletions src/util/dom.ts
Original file line number Diff line number Diff line change
Expand Up @@ -84,12 +84,32 @@ export default class DOM {
}, 0);
}

public static mousePos(el: HTMLElement, e: MouseEvent | Touch) {
const rect = el.getBoundingClientRect();
public static getScale(element: HTMLElement) {
const rect = element.getBoundingClientRect(); // Read-only in old browsers.

return {
x: rect.width / element.offsetWidth || 1,
y: rect.height / element.offsetHeight || 1,
boundingClientRect: rect,
};
}

public static mousePos(el: HTMLElement, ev: MouseEvent | Touch) {
// Uses technique from https://github.com/Leaflet/Leaflet/pull/6055
if (!el) {
return new Point(ev.clientX, ev.clientY);
}

const scale = DOM.getScale(el),
offset = scale.boundingClientRect; // left and top values are in page scale (like the event clientX/Y)

return new Point(
e.clientX - rect.left - el.clientLeft,
e.clientY - rect.top - el.clientTop
// offset.left/top values are in page scale (like clientX/Y),
// whereas clientLeft/Top (border width) values are the original values (before CSS scale applies).
(ev.clientX - offset.left) / scale.x - el.clientLeft,
(ev.clientY - offset.top) / scale.y - el.clientTop
);

}

public static touchPos(el: HTMLElement, touches: TouchList) {
Expand Down

0 comments on commit 17f5572

Please sign in to comment.