Get the center point of a DOMRect
Return [x, y] of the rect’s center.
function getCenter({ x, y, width, height }) { return [x + width / 2, y + height / 2]; }
Input & expected output
Input
{
"x": 0,
"y": 0,
"width": 200,
"height": 400
}Expected output
[
100,
200
]The edge case
Input
{
"x": 10,
"y": 10,
"width": 0,
"height": 0
}Expected output
[
10,
10
]Know the limits
- Coordinates are in the rect’s own space: viewport pixels for getBoundingClientRect(). Add window.scrollX and scrollY for document coordinates.
The function above is the implementation used by the lab. The lab validates JSON types and caps size before execution; include equivalent validation when accepting untrusted input in your application.
Source & maintenance
Based on Get the center point of a DOMRect from the original 1loc collection by Nguyen Huu Phuoc. Copyright (c) 2020 phuoc-ng. MIT licensed.
Reads x and y so plain JSON rects work; runs in the lab. Original MDX retained as inert source evidence.
Maintained by Oveyon. Source commit: 14b481cf60df. Read the license.
Keep exploring
- Check if a given DOMRect is contained within another DOMRect — True when the target lies inside the container or on its edges.
- Check if two DOMRects intersect — Two rects intersect when they meet on both axes.
- Compare two DOMRects for size and position match — Compare x, y, width and height exactly.