Generate SVG Labels

by Dawid Ryłko

HTML

<div id="test"></div>

CSS

body {
  background-color: #616666;
}

.path {
  stroke-dasharray: 1000;
  stroke-dashoffset: 1000;
  animation: dash 5s linear forwards;
}

@keyframes dash {
  from {
    stroke-dashoffset: 1000;
  }
  to {
    stroke-dashoffset: 0;
  }
}

JavaScript

const BEGIN_PATH =
  "M4 1V1C2.34315 1 1 2.34315 1 4V24C1 25.6569 2.34315 27 4 27";
const END_PATH =
  "M0.941999 27H0C1.8418 27 2.69408 26.5961 3.26387 25.8997L11.4457 15.8997C12.3499 14.7946 12.3499 13.2054 11.4457 12.1003L3.26387 2.10029C2.69408 1.40388 1.8418 1 0.941999 1H0";
const HEIGHT = 28;
const OFFSET = 4;
const STROKE_WIDTH = 2;

const DEFAULT_STROKE_COLOR = "#919191";
const BACKGROUND_COLOR = "#1F1F1F";
const TEXT_COLOR = "#FFFFFF";
const MONOSPACED_FONT = "monospace";
const CHAR_WIDTH = OFFSET * 2;

function measurePathWidth(path) {
  const segments = path.match(/[a-zA-Z][^a-zA-Z]*/g);

  let minX = Infinity;
  let maxX = -Infinity;

  segments.forEach((segment) => {
    const values = segment
      .slice(1)
      .trim()
      .split(/[\s,]+/)
      .map(parseFloat);

    for (let i = 0; i < values.length; i += 2) {
      const x = values[i];
      if (!isNaN(x)) {
        minX = Math.min(minX, x);
        maxX = Math.max(maxX, x);
      }
    }
  });

  return maxX - minX;
}

function shiftPath(path, shiftX) {
  const segments = path.match(/[a-zA-Z][^a-zA-Z]*/g);

  const shiftedSegments = segments.map((segment) => {
    const command = segment[0];
    const values = segment
      .slice(1)
      .trim()
      .split(/[\s,]+/)
      .map(parseFloat);

    for (let i = 0; i < values.length; i += 2) {
      values[i] += shiftX;
    }

    return command + values.join(" ");
  });

  return shiftedSegments.join(" ");
}

function createSVGPath(connectedPath, stroke, strokeWidth, fill) {
  const path = document.createElementNS("http://www.w3.org/2000/svg", "path");
  path.setAttribute("d", connectedPath);
  path.setAttribute("stroke", stroke);
  path.setAttribute("stroke-width", strokeWidth);
  path.setAttribute("fill", fill || DEFAULT_STROKE_COLOR);
  path.setAttribute("class", "path")
  return path;
}

function createTextElement(text, x, stroke) {
  const textElement = document.createElementNS(
    "http://www.w3.org/2000/svg",
    "text"
  );
 ...