Skip to content

Instantly share code, notes, and snippets.

@awstanley
Created September 26, 2020 12:29
Show Gist options
  • Save awstanley/5660b47b4e47d8d832764ee1c1231245 to your computer and use it in GitHub Desktop.
Save awstanley/5660b47b4e47d8d832764ee1c1231245 to your computer and use it in GitHub Desktop.
Demonstration of SVG creation in JavaScript.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>SVG Inject Test</title>
</head>
<body>
<script>
// Simple pathPath which is just a box with a point injected and raised. Nothing fancy!
let path = "M 3.9115288,12.97346 15.805024,2.3901266 27.698518,12.97346 V 33.152308 H 3.9115288 Z";
// This isn't required, but it's an SVG style to make the point.
let style = "opacity:0.75;fill:#729fcf;stroke-width:0.264583";
// Namespace
let svgNS = "http://www.w3.org/2000/svg";
// DOM elements, which require the namespace.
let domSVG = document.createElementNS(svgNS, "svg");
let domPath = document.createElementNS(svgNS, "path");
// Build the path
domPath.setAttribute("d", path);
domPath.setAttribute("style", style);
// Inject and build the SVG.
domSVG.appendChild(domPath);
domSVG.setAttribute("xmlns", "http://www.w3.org/2000/svg");
// This has to be case sensitive.
// Note that not adding the namespace doesn't hurt us here.
// (Should probably use it as we have it anyway!)
domSVG.setAttributeNS(svgNS, "viewBox", "0 0 40 40");
// I don't want it massive, and SVGs scale!
domSVG.setAttribute("width", "40");
domSVG.setAttribute("height", "40");
// Append it to the body.
document.body.appendChild(domSVG);
</script>
<script>
// Just to make the point you can access it.
let svg = document.getElementsByTagName("svg")[0];
console.log(svg);
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment