Skip to content

Geometry ​

Everything here works in world units, the coordinates the elements are stored in. A Point is { x, y } and a Rect is { x, y, w, h }, both from @adecore/utils/geometry, which also holds the math on them. The app converts pointer pixels through its zoom and pan; no function reads the DOM.

tsx
import { boundsOf, boundsOfElements, DEFAULT_SVG_MARGIN, elementAt, handlePoint, RESIZE_HANDLES, toSvg } from '@adecore/drawing';
import type { DrawingElement } from '@adecore/drawing/protocol';
import { useState, type PointerEvent } from 'react';
import { THEME_EDGE, THEME_PALETTE, THEME_PAPER } from '../shared/canvas-theme.ts';
import { SKETCH } from '../shared/sketch.ts';

const SVG = toSvg(SKETCH, { palette: THEME_PALETTE, paper: THEME_PAPER, edge: THEME_EDGE });

// The same box toSvg gives its viewBox, so a pointer maps onto world units.
const bounds = boundsOfElements(SKETCH)!;
const VIEW = { x: bounds.x - DEFAULT_SVG_MARGIN, y: bounds.y - DEFAULT_SVG_MARGIN, w: bounds.w + DEFAULT_SVG_MARGIN * 2, h: bounds.h + DEFAULT_SVG_MARGIN * 2 };

export default function DrawingHitTestDemo() {
    const [hovered, setHovered] = useState<DrawingElement | null>(null);

    function onPointerMove(event: PointerEvent<HTMLDivElement>) {
        const area = event.currentTarget.getBoundingClientRect();
        const point = {
            x: VIEW.x + ((event.clientX - area.left) / area.width) * VIEW.w,
            y: VIEW.y + ((event.clientY - area.top) / area.height) * VIEW.h
        };

        setHovered(elementAt(SKETCH, point, 6) ?? null);
    }

    const box = hovered ? boundsOf(hovered) : null;

    return (
        <div className="flex w-full flex-col gap-3">
            <div className="relative" onPointerMove={onPointerMove} onPointerLeave={() => setHovered(null)}>
                <div className="[&_svg]:h-auto [&_svg]:w-full" dangerouslySetInnerHTML={{ __html: SVG }} />
                {box && (
                    <svg className="pointer-events-none absolute inset-0 h-full w-full" viewBox={`${VIEW.x} ${VIEW.y} ${VIEW.w} ${VIEW.h}`}>
                        <rect x={box.x} y={box.y} width={box.w} height={box.h} fill="none" stroke="var(--accent)" strokeDasharray="4 4" />
                        {RESIZE_HANDLES.map((handle) => {
                            const at = handlePoint(box, handle);

                            return <rect key={handle} x={at.x - 4} y={at.y - 4} width={8} height={8} fill="var(--surface)" stroke="var(--accent)" />;
                        })}
                    </svg>
                )}
            </div>
            <p className="font-mono text-code text-text-muted">elementAt: {hovered ? `${hovered.kind} "${hovered.id}"` : 'undefined'}</p>
        </div>
    );
}

The demo asks elementAt what is under the pointer and draws its boundsOf with a handle at every handlePoint. The inside of the ellipse is no hit, because it has no fill.

Bounds ​

  • boundsOf(element) is the stored box of one element. boundsOfElements(elements) is the box around all of them, or null for none.
  • toSvg and elementsIn use the stored box turned by the element's angle.

No box includes the wobble, stroke width, arrow heads or text that runs past a note. Add room for those when you fit a view to its content.

Rotation ​

angle turns an element around the center of its box, in radians. rotatePoint(point, around, angle) from @adecore/utils/geometry turns a point. Turn it by minus the element's angle around centerOf(boundsOf(element)) to get it in the element's own frame.

Hit tests ​

ts
import { elementAt, elementsIn } from '@adecore/drawing';
import { rectFromPoints } from '@adecore/utils/geometry';

const hit = elementAt(elements, pointer, 6 / zoom);
const picked = elementsIn(elements, rectFromPoints(dragStart, pointer));

elementAt decides each element after undoing its rotation:

KindA hit
rect, diamond, ellipseAnywhere inside when it has a fill, else near the outline
text, noteAnywhere inside the box; the tolerance does not widen it
line, freehandNear the polyline through its points, or near the only point of a stroke

"Near" is within tolerance or the stroke width, whichever is larger, measured to the ideal outline without wobble.

elementAt(elements, point, tolerance) returns the topmost element hit, or undefined. elementsIn(elements, rect) returns every element whose drawn box overlaps the rect, in stacking order. Both skip locked elements. A lock only keeps an element out of selection, so check it again where the app writes.

Resizing ​

RESIZE_HANDLES lists the eight handles of a box (ResizeHandle), clockwise from nw, and handlePoint(rect, handle) places one. While a handle is dragged, resizeRect(rect, handle, pointer, aspect) returns the new box with the opposite side fixed. With aspect set (usually Shift) the box keeps its proportions.

resizeRect does not clamp. A handle dragged past the opposite side gives a negative size, which the app normalizes or refuses before it stores the box.

ts
import { boundsOf, resizeRect, scaleElement } from '@adecore/drawing';

const from = boundsOf(element);
const to = resizeRect(from, 'se', pointer, event.shiftKey);
const resized = scaleElement(element, from, to);

scaleElement(element, from, to) moves and scales an element from one box to another; for a selection, pass the box around all of it as from. It scales the points of a line or stroke. A text gets sized: true, so it wraps to its box from then on. The angle, seed, stroke width, font size and corner radius stay. Both functions work on the unturned box, so turn the pointer of a rotated element into its frame with rotatePoint first.

Licenses and third-party notices are listed in each package.