👔MouseEvent+ext
Last updated
Last updated
browser ⟩ event ⟩ type ⟩ mouse ⟩ +ext
extend MouseEvent.
// 🔸 .pointInViewport
// 🔸 .pointInPage
// 🔸 .pointInScreen
// 🔹 .pointInElement()
replit ⟩ click to move ball
// 2023.01.21 - 12:20 (•) first draft
// -------------------------------------------------------
// ⭐ import
import {vec, linearCombination} from './Vector.js'; // 👔 Vector
// -------------------------------------------------------
// ⭐ MouseEvent + ext
// -------------------------------------------------------
// 🔸 .pointInViewport
// 🔸 .pointInPage
// 🔸 .pointInScreen
// 🔹 .pointInElement()
//
Object.defineProperties(MouseEvent.prototype, {
// 🔸 .pointInViewport
pointInViewport: {
get() {
return vec(this.clientX, this.clientY);
},
},
// 🔸 .pointInPage
pointInPage: {
get() {
return vec(this.pageX, this.pageY);
},
},
// 🔸 .pointInScreen
pointInScreen: {
get() {
return vec(this.screenX, this.screenY);
},
},
// 🔹 .pointInElement()
// - relative to element's "padding box" origin
pointInElement: {
value: function(elem = this.target) {
const a = this.pointInViewport;
const b = elem.boundingBox.origin;
const c = elem.paddingBox.origin;
// v = a - (b + c)
return linearCombination([1, -1, -1], [a, b, c]);
},
},
});
// ⭐ export
export {}; // ES module
replit ⟩ click to move ball (this example)
const { log } = console
// ⭐️ import
import { $ } from './js/ext/Node_ext.js'; // 👔 Node + ext
import { rect } from './js/ext/Rect.js'; // 👔 Rect
import { } from './js/ext/Element+boxes.js'; // 👔 Element + boxes
import { } from './js/ext/MouseEvent+ext.js'; // 👔 MouseEvent + ext
// --------------------------------------------------------------------
// elements
const ball = $("#ball"); // 👔 Node + ext
const field = $("#field");
const info = $("#info");
const ballSize = ball.paddingBox.size; // 👔 Element + boxes
const {width: w, height: h} = field.paddingBox.size;
const dx = ballSize.width/2;
// ⭐️ event handlers
// -------------------------------------------------------
// field.onclick
field.onclick = (event) => {
// calculate ball's (constrained) new origin
const {x, y} = event
// mouse cursor point
.pointInElement(field)
// constrain center in "inset" rect
.clampInRect(rect(dx, dx, w-2*dx, h-2*dx)) // 👔 Rect
// translate to top left corner
.plus(ballSize.vector.times(-0.5));
// update ball's position
ball.style.left = x + 'px';
ball.style.top = y + 'px';
};
// document.onmousemove
document.onmousemove = (e) => {
info.innerHTML = `• screen: ${e.pointInScreen}<br>` // 👔 MouseEvent + ext
+ `• page : ${e.pointInPage}<br>`
+ `• viewport: ${e.pointInViewport}<br>`
+ `• field: ${e.pointInElement(field)}`;
};