Skip to content

Instantly share code, notes, and snippets.

@adrianseeley
Created April 13, 2020 12:08
Show Gist options
  • Save adrianseeley/459cd6eb47b3d9b5bad08396a02e4812 to your computer and use it in GitHub Desktop.
Save adrianseeley/459cd6eb47b3d9b5bad08396a02e4812 to your computer and use it in GitHub Desktop.
SVG HTML
<html>
<body id="body">
<div id="svgparent"></div>
<button id="download">Download SVG</button>
</body>
<script>
const cutColor = "red";
const labelColor = "blue";
const createSVG = (w, h) => {
const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
svg.setAttribute("xmlns", "http://www.w3.org/2000/svg");
svg.setAttribute("width", w);
svg.setAttribute("height", h);
return svg;
};
const cutRect = (x, y, w, h) => {
const ele = document.createElementNS("http://www.w3.org/2000/svg", "rect");
ele.setAttribute("x", x);
ele.setAttribute("y", y);
ele.setAttribute("width", w);
ele.setAttribute("height", h);
ele.setAttribute("fill", "none");
ele.setAttribute("stroke", cutColor);
ele.setAttribute("stroke-linecap", "butt");
ele.setAttribute("stroke-width", "1");
svg.appendChild(ele);
};
const cutCircle = (cx, cy, r) => {
const ele = document.createElementNS("http://www.w3.org/2000/svg", "circle");
ele.setAttribute("cx", cx);
ele.setAttribute("cy", cy);
ele.setAttribute("r", r);
ele.setAttribute("fill", "none");
ele.setAttribute("stroke", cutColor);
ele.setAttribute("stroke-linecap", "butt");
ele.setAttribute("stroke-width", "1");
svg.appendChild(ele);
return ele;
};
const svg = createSVG(7000, 3000);
cutRect(0, 0, 7000, 3000);
cutRect(100, 100, 1000, 1000);
cutCircle(500, 500, 100);
const svgParent = document.getElementById("svgparent");
svgParent.appendChild(svg);
document.getElementById("download").onclick = () => {
const filename = "render.svg";
const data = svgParent.innerHTML;
const file = new File([data], filename, {type: "image/svg+xml"});
const url = URL.createObjectURL(file);
const elem = window.document.createElement('a');
elem.href = window.URL.createObjectURL(file);
elem.download = filename;
document.body.appendChild(elem);
elem.click();
document.body.removeChild(elem);
};
</script>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment