Skip to content

Instantly share code, notes, and snippets.

@mlewand
Last active July 18, 2024 19:49
Show Gist options
  • Save mlewand/56237c19050d27f61b807ed384dff2db to your computer and use it in GitHub Desktop.
Save mlewand/56237c19050d27f61b807ed384dff2db to your computer and use it in GitHub Desktop.
DOMRect visualisation - a small helper for visualizing DOMRect objects.
( function() {
/**
* A helper function to visualize DOMRect or set of DOMRect instances.
*
* Subsequent calls will remove previously marked elements.
*
* Debug a element currently focused in your devtools inspector.
* window.markRect( $0.getBoundingClientRect() );
* // Debug a selection.
* window.markRect( document.getSelection().getRangeAt( 0 ).getClientRects() );
*/
var drawnRect = [];
/**
* @param {DOMRect/DOMRect[]} rectangles
*/
window.markRect = function( rectangles ) {
// Cleanup.
drawnRect.forEach( function( oldRect ) {
oldRect.remove();
} );
// Unify format.
if ( typeof rectangles.length == 'undefined' ) {
rectangles = [ rectangles ];
} else {
rectangles = Array.from( rectangles );
}
rectangles.forEach( function( rect ) {
var curDrawing = createRectDraw(),
dims = [ 'top', 'left', 'width', 'height' ];
dims.forEach( function( property ) {
curDrawing.style[ property ] = rect[ property ] + 'px';
} );
console.log( 'created debug rect:', curDrawing );
drawnRect.push( curDrawing );
} );
}
function createRectDraw() {
var ret = document.createElement( 'div' );
ret.style.position = 'absolute';
ret.style.outline = '2px solid red';
ret.className = 'debug-rect-marker';
document.body.appendChild( ret );
return ret;
}
} )();
@Sv443
Copy link

Sv443 commented Sep 29, 2021

Thank you, this is exactly what I've been looking for!
I needed some more advanced stuff so I made an improved version that adds a few features and ES6 syntax (here)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment