Skip to content

Instantly share code, notes, and snippets.

@netsi1964
Created February 21, 2021 10:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save netsi1964/2495a106c168f8150f52cb2023705e6b to your computer and use it in GitHub Desktop.
Save netsi1964/2495a106c168f8150f52cb2023705e6b to your computer and use it in GitHub Desktop.
Takes a website and creates a SVG of it
Element.prototype.getDirectDesc = function () {
const descendants = Array.from(this.querySelectorAll("*"));
const directDescendants = descendants.filter(
(ele) =>
ele.parentElement === this &&
!["script", "iframe"].includes(ele.nodeName.toLowerCase())
);
return directDescendants;
};
function getSVG(fromEle, isChild) {
if (isChild) {
svg += `<g class="${fromEle.nodeName.toLowerCase()} asContainer">`;
}
if (fromEle.getDirectDesc().length > 0) {
const children = fromEle.getDirectDesc();
for (ele of children) {
const style = getComputedStyle(ele);
if (
ele.getDirectDesc().length > 0 &&
!["script", "iframe", "svg"].includes(ele.nodeName.toLowerCase())
) {
getSVG(ele, true);
} else {
svg += getElement(ele);
}
}
} else {
svg += getElement(fromEle);
}
if (isChild) {
svg += `</g>`;
}
}
function getElement(ele) {
const BBOX = ele.getBoundingClientRect();
const width = parseInt(BBOX.width);
const height = parseInt(BBOX.height);
const left = parseInt(BBOX.left);
const top = parseInt(BBOX.top);
if (width === 0 || height === 0) {
return "";
}
if (["img", "picture", "svg"].includes(ele.nodeName.toLowerCase())) {
return `<image href="http://dummyimage.com/${width}x${height}" y="${top}" x="${left}" height="${height}" width="${width}" />`;
} else {
return `<text x="${left}" y="${top}">${ele.textContent.trim()}</text>`;
}
}
var svg = "";
function generateSVGOfPage() {
const { width, height } = document.body.getBoundingClientRect();
svg = `<svg width="${width}" height="${height}" viewBox="0 0 ${width} ${height}">`;
getSVG(document.body);
svg += "</svg>";
return svg;
}
copy(generateSVGOfPage(document.body));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment