Last active
July 18, 2024 19:49
-
-
Save mlewand/56237c19050d27f61b807ed384dff2db to your computer and use it in GitHub Desktop.
DOMRect visualisation - a small helper for visualizing DOMRect objects.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
( 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; | |
} | |
} )(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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)