โœจclick to move ball

browser โŸฉ event โŸฉ type โŸฉ mouse โŸฉ click โŸฉ 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