๐MouseEvent+ext
browser โฉ event โฉ type โฉ mouse โฉ +ext
extend MouseEvent.
// ๐ธ .pointInViewport
// ๐ธ .pointInPage
// ๐ธ .pointInScreen
// ๐น .pointInElement()
๐ custom
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)}`;
};
Last updated