click to move ball

browsereventtypemouseclick ⟩ example ⟩ click to move ball

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