A small single-file project using HTML, CSS, and JavaScript. Select a shape from a dropdown and print it with *.

Examples target any modern browser. No libraries needed.

How it works

  1. Dropdown selects the shape.
  2. Inputs change based on shape: rectangle needs width + height, square needs size, triangle needs height.
  3. JavaScript builds the pattern with loops and '*'.repeat(n).
  4. Output shows in a <pre> block.

The JavaScript

function printRectangle(width, height) {
  let result = '';
  for (let i = 0; i < height; i++) {
    result += '*'.repeat(width) + 'n';
  }
  return result;
}

function printSquare(size) {
  return printRectangle(size, size);
}

function printTriangle(height) {
  let result = '';
  for (let i = 1; i <= height; i++) {
    result += '*'.repeat(i) + 'n';
  }
  return result;
}

function printShape() {
  const shape = document.getElementById('shape').value;
  const width = parseInt(document.getElementById('width').value, 10);
  const height = parseInt(document.getElementById('height').value, 10);
  if (shape === 'rectangle') return printRectangle(width, height);
  if (shape === 'square') return printSquare(width);
  if (shape === 'triangle') return printTriangle(height);
}

Example output

Rectangle 10×3:

**********
**********
**********

Square 4×4:

****
****
****
****

Triangle height 4:

*
**
***
****

Full single-file code

Save as shapes.html and open in a browser. See rectangle.html in this repo for the complete working version with dropdown and styling.

Related DevStackIO Resources

References

  1. String.prototype.repeat() – https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/repeat
  2. HTML select element – https://developer.mozilla.org/en-US/docs/Web/HTML/Element/select
  3. Document.getElementById() – https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementById

Keep going on DevStackIO

Learning scripting fundamentals in another shell helps too: see PowerShell commands beginners should know.

Related Tools

Try these companion tools on DevStackIO Tools: