Demo Rutas

by academiax

HTML

<svg id="svg-container"></svg>

JavaScript

// Define the JSON data
const json = [
  "HTML",
  "CSS",
  "JavaScript",
  "Web APIs",
  "React"
];

// Set up the SVG canvas
const svgNS = "http://www.w3.org/2000/svg";
const svgContainer = document.getElementById("svg-container");
const rectSpacing = 10;
const lineColor = "blue";
const lineWidth = 3;
const rectWidth = 150;
const rectHeight = 30;

function createRectangle(yOffset) {
  // Create rectangle element
  const rect = document.createElementNS(svgNS, "rect");
  rect.setAttribute("x", 0);
  rect.setAttribute("y", yOffset);
  rect.setAttribute("width", rectWidth);
  rect.setAttribute("height", rectHeight);
  rect.setAttribute("fill", "yellow");
  rect.setAttribute("stroke", "black");
  rect.setAttribute("stroke-width", "2");
  svgContainer.appendChild(rect);
}

function createText(text, yOffset) {
  // Create text element
  const textElem = document.createElementNS(svgNS, "text");
  textElem.setAttribute("x", rectWidth / 2);
  textElem.setAttribute("y", yOffset + (rectHeight / 2));
  textElem.setAttribute("dominant-baseline", "middle");
  textElem.setAttribute("text-anchor", "middle");
  textElem.setAttribute("fill", "black");
  textElem.textContent = text;
  svgContainer.appendChild(textElem);
}

function createLine(yOffset) {
  const line = document.createElementNS(svgNS, "line");
  line.setAttribute("x1", rectWidth/2);
  line.setAttribute("y1", yOffset - rectSpacing);
  line.setAttribute("x2", rectWidth/2);
  line.setAttribute("y2", yOffset);
  line.setAttribute("stroke", lineColor);
  line.setAttribute("stroke-width", lineWidth);
  svgContainer.appendChild(line);
}

// Loop through the JSON data and generate SVG elements
let yOffset = 0;
for (let i = 0; i < json.length; i++) {
  const text = json[i];

  createRectangle(yOffset);
  createText(text, yOffset);

  // Create line element
  if (i > 0) {
		createLine(yOffset);
  }

  // Increment y offset for next element
  yOffset += rectHeight + rectSpacing;
}

// Set SVG canvas height based on total...