Stack (final)

by butterfreeDay

HTML

<h1>Stack Project</h1>
<div id="input_area">
  <input id="value_box" type="text" size="7"><br>
  <button id="push">
    Push
  </button>
  <button id="pop">
    Pop
  </button>
</div>
<div id="canvas">
  <svg id="svg_area" xmlns="http://www.w3.org/2000/svg" width="600" height="400">
  </svg>
</div>

JavaScript

class Rectangle {
  constructor(width, height, x, y, label) {
    this.width = width;
    this.height = height;
    this.x = x;
    this.y = y;
    this.label = label;
  }
  toString() {
    return this.width + "," + this.height;
  }
  toSVG() {
    const svgNS = "http://www.w3.org/2000/svg";
    let svg = document.createElementNS(svgNS, "svg");
    svg.setAttribute("id", this.id);
    svg.setAttribute("x", this.x);
    svg.setAttribute("y", this.y);
    let rect = document.createElementNS(svgNS, "rect");
    rect.setAttribute("x", 2);
    rect.setAttribute("y", 2);
    rect.setAttribute("width", this.width);
    rect.setAttribute("height", this.height);
    rect.setAttribute("style","fill: white; stroke: black; stroke-width: 4");
    svg.appendChild(rect);
    let text = document.createElementNS(svgNS, "text");
    text.setAttribute("x",this.width/2 + 2);
    text.setAttribute("y",this.height/2 + 7);
    text.setAttribute("text-anchor","middle");
    text.appendChild(document.createTextNode(this.label));
    svg.appendChild(text);
    return svg;
  }
}
let stack_array = [];
function removeChildren(parent) {
	while (parent.childNodes.length > 0) {
  	parent.removeChild(parent.childNodes[0]);
  }
}
function handlePush() {
   const value_box = document.getElementById("value_box");
   let label = value_box.value;
   stack_array.unshift(label);
   value_box.value = "";
   drawStack();
   //console.log(stack_array);
}
function drawStack() {
	const svg_area = document.getElementById("svg_area");
  removeChildren(svg_area);
  let y_start = 10;
	for (let i = 0; i < stack_array.length; i++) {
  	let rect = new Rectangle(50,30,20,y_start + (i*40),
    	stack_array[i]);
    svg_area.appendChild(rect.toSVG());
  }
}
function handlePop() {
	let removed_value = stack_array.shift();
  const value_box = document.getElementById("value_box");
  value_box.value = removed_value;
  drawStack();
}
function init() {
	const push = document.getElementById("push");
 ...