Skip to content

Instantly share code, notes, and snippets.

@jarretgabel
Last active January 9, 2018 00:47
Show Gist options
  • Save jarretgabel/57237403e69e8421713df122d3c122e9 to your computer and use it in GitHub Desktop.
Save jarretgabel/57237403e69e8421713df122d3c122e9 to your computer and use it in GitHub Desktop.
method i use to create svgs dyamically
createSVG(opts) {
let svg = document.createElementNS("http://www.w3.org/2000/svg", opts.type);
if(opts.type === "text") {
let anchor = "middle";
if(opts.anchor) {
anchor = opts.anchor;
}
let alignment = "auto";
if(opts.alignment) {
alignment = opts.alignment;
}
svg.setAttribute("x", opts.x);
svg.setAttribute("y", opts.y);
svg.setAttribute("text-anchor", opts.anchor);
svg.setAttribute("alignment-baseline", alignment);
} else if(opts.type === "line") {
svg.setAttribute("x1", opts.x1);
svg.setAttribute("y1", opts.y1);
svg.setAttribute("x2", opts.x2);
svg.setAttribute("y2", opts.y2);
if(opts.style === "dotted") {
svg.setAttribute("stroke-dasharray", "1, 2");
svg.setAttribute("stroke-width", "1");
}
} else if(opts.type === "path") {
svg.setAttribute("d", opts.d);
} else if(opts.type === "circle") {
svg.setAttribute("cx", opts.cx);
svg.setAttribute("cy", opts.cy);
svg.setAttribute("r", opts.r);
} else if(opts.type === "rect") {
svg.setAttribute("x", opts.x);
svg.setAttribute("y", opts.y);
svg.setAttribute("width", opts.width);
svg.setAttribute("height", opts.height);
}
if(opts.className) {
svg.setAttribute("class", opts.className);
}
if(opts.caption) {
svg.textContent = opts.caption;
}
return svg;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment