Last active
August 29, 2015 14:06
-
-
Save netsi1964/0b17af444ccdf3696114 to your computer and use it in GitHub Desktop.
Convert element bounding boxes into SVG rectangles
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
var svg = ""; | |
var miX = 10000, | |
miY = 10000, | |
maX = -1, | |
maY = -1, | |
fillColor = "rgba(100,100,100,.14)", | |
strokeColor = "rgba(250,250,100,.8)", | |
strokeWidth = "4px", | |
lineStokeColor = "rgba(100,100,100,.8)", | |
lineStrokeWidth = "1px", | |
excludeNegativePositionedElements = true; | |
var elements = document.querySelectorAll("body *"); | |
[].forEach.call(elements, function (element) { | |
var boundingRect = element.getBoundingClientRect(); | |
var x = boundingRect.left; | |
var y = boundingRect.top; | |
var r = boundingRect.right; | |
var b = boundingRect.bottom; | |
var width = boundingRect.width; | |
var height = boundingRect.height; | |
if (width === 0 || height === 0) {} else { | |
miX = (miX < x) ? miX : x; | |
miY = (miY < y) ? miY : y; | |
maX = (maX > r) ? maX : r; | |
maY = (maY > b) ? maY : b; | |
var isNegativePosition = (x < 0 || y < 0); | |
if (excludeNegativePositionedElements && isNegativePosition) { | |
// Element is positioned negative and they are not wanted | |
} else { | |
var tagName = element.tagName.toLowerCase(); | |
var sLine = ""; | |
if (tagName === "img") { | |
sLine = "\n<line x1=\"" + x + "\" y1=\"" + y + "\" x2=\"" + r + "\" y2=\"" + b + "\" />\n"; | |
sLine += "\n<line x1=\"" + r + "\" y1=\"" + y + "\" x2=\"" + x + "\" y2=\"" + b + "\" />\n "; | |
} | |
var text = element.innerText.substr(0, 50).replace(/\"/g, """); | |
var sElement = '<rect x="' + x + '" y="' + y + '" width="' + width + '" height="' + height + '">'; | |
sElement += '<title>' + tagName + ((text.length !== 0) ? ': "' + text + '"' : '') + '</title>\n'; | |
sElement += "</rect>\n"; | |
sElement += sLine; | |
svg += sElement; | |
} | |
} | |
}); | |
var contents = svg; | |
svg = '<svg width="' + (maX - miX) + '" height="' + (maY - miY) + '">'; | |
svg += "<defs><style>"; | |
svg += "rect {fill: " + fillColor + ";}"; | |
svg += "rect:hover {stroke: " + strokeColor + "; stroke-width: " + strokeWidth + ";}"; | |
svg += "line {stroke: " + lineStokeColor + "; stroke-width: " + lineStrokeWidth + ";}"; | |
svg += "</style></defs>"; | |
svg += contents; | |
svg += '</svg>'; | |
var textarea = "<textarea style=\"width: 100%; height: 300px;\"><?xml version=\"1.0\"?>\n" + svg + "</textarea>"; | |
var win = window.open(""); | |
win.document.write(svg + textarea); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment