The Logo creator project: a logo generator in JavaScript

Lesson 16 of 17 · HTML, CSS and JavaScript

The heart of the site: the page where the user types a name, chooses a colour, a shape and a font, immediately sees the logo, and then downloads it as an image. We draw the logo as SVG – a vector image made of HTML-like elements, so JavaScript changes it the same way as the rest of the page.

Before you start: required prior knowledge – home page styles, DOM and events.
How to learn: do the tasks at the end on your own in your editor first; open the hint and the solution only after that. Every example has the code and a live result below it; type the code into your own file and change it.

SVG: an image written in code

<svg viewBox="0 0 300 120" width="300" style="border:1px solid #ccc">
  <circle cx="60" cy="60" r="45" fill="#dd0022" />                  <!-- circle: centre and radius -->
  <rect x="120" y="20" width="70" height="70" rx="12" fill="#1f5f91" /> <!-- rectangle, rx = rounding -->
  <polygon points="250,15 290,60 250,105 210,60" fill="#2a9d5c" />   <!-- polygon: a list of points -->
  <text x="60" y="72" text-anchor="middle" font-size="32" font-weight="bold" fill="white">SP</text>
</svg>

Result:

ElementAttributes
<svg viewBox="0 0 300 120">a "canvas" of 300×120 units; the image is enlarged without losing sharpness
circlecx, cy – centre, r – radius
rectx, y – the top left corner, width, height, rx
polygonpoints – pairs of coordinates
textx, y, text-anchor="middle" – centred around x
fillthe fill colour

The coordinate system is like in mathematics, but y grows downwards – the point (0, 0) is the top left corner. Processing and Python turtle/pygame use the same system.

The generator.html page

On the left is the form (Bootstrap), on the right an empty div id="prikaz" (the preview) into which JavaScript draws the logo:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Generator – Logo Creator</title>
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css">
  <link rel="stylesheet" href="css/main.css">
</head>
<body class="bg-light">
  <div class="container py-4">
    <h1 class="h3 mb-4"><a href="naslovna.html" class="text-decoration-none">Logo Creator</a> · generator</h1>
    <div class="row g-4">
      <!-- left: the choices -->
      <form id="forma" class="col-md-5">
        <div class="mb-3">
          <label for="naziv" class="form-label">Name</label>
          <input id="naziv" class="form-control" maxlength="20" value="Logo">
        </div>
        <div class="mb-3">
          <label for="slogan" class="form-label">Slogan (optional)</label>
          <input id="slogan" class="form-control" maxlength="30">
        </div>
        <div class="row g-2 mb-3">
          <div class="col">
            <label for="boja" class="form-label">Colour</label>
            <input id="boja" type="color" class="form-control form-control-color w-100" value="#dd0022">
          </div>
          <div class="col">
            <label for="oblik" class="form-label">Shape</label>
            <select id="oblik" class="form-select">
              <option value="krug">circle</option>
              <option value="kvadrat">square</option>
              <option value="romb">diamond</option>
            </select>
          </div>
        </div>
        <div class="mb-3">
          <label for="font" class="form-label">Font</label>
          <select id="font" class="form-select">
            <option value="Arial, sans-serif">Arial</option>
            <option value="Georgia, serif">Georgia</option>
            <option value="'Courier New', monospace">Courier New</option>
          </select>
        </div>
        <button type="button" id="preuzmiSvg" class="btn btn-danger">Download SVG</button>
        <button type="button" id="preuzmiPng" class="btn btn-outline-danger">Download PNG</button>
      </form>
      <!-- right: the live preview -->
      <div class="col-md-7 text-center">
        <div id="prikaz" class="p-3 bg-white rounded shadow-sm"></div>
      </div>
    </div>
  </div>
  <script src="js/generator.js"></script>
</body>
</html>
Note: the ids of the fields (naziv = name, boja = colour, oblik = shape, prikaz = preview) and the shape values (krug = circle, kvadrat = square, romb = diamond) are the same as in the other lessons of the project – the home page sends ?naziv=..., and the Django lessons use the same names in the database.

JavaScript: drawing and the live preview

// ===== js/generator.js – Logo Creator =====
const NS = "http://www.w3.org/2000/svg";       // SVG elements are created with this "namespace"
const fields = ["naziv", "slogan", "boja", "oblik", "font"].map(id => document.getElementById(id));
const [nameField, sloganField, colorField, shapeField, fontField] = fields;
const preview = document.getElementById("prikaz");

// 1. the name from the address: generator.html?naziv=Pupin+Club (sent by the form on the home page)
const fromAddress = new URLSearchParams(location.search).get("naziv");
if (fromAddress) nameField.value = fromAddress.slice(0, 20);

// helper function: create an SVG element with attributes
function el(name, attributes) {
  const e = document.createElementNS(NS, name);
  for (const [k, v] of Object.entries(attributes)) e.setAttribute(k, v);
  return e;
}

// initials: "Pupin Club" -> "PC", "Logo" -> "LO"
function initials(text) {
  const words = text.trim().split(/\s+/).filter(w => w.length > 0);
  if (words.length === 0) return "?";
  if (words.length === 1) return words[0].slice(0, 2).toUpperCase();
  return (words[0][0] + words[1][0]).toUpperCase();
}

// 2. draw the logo from the current values of the fields
function draw() {
  const svg = el("svg", { xmlns: NS, viewBox: "0 0 400 200", width: "100%" });
  svg.id = "logo";
  const c = colorField.value;

  // the sign (left)
  if (shapeField.value === "krug") svg.append(el("circle", { cx: 100, cy: 100, r: 70, fill: c }));
  else if (shapeField.value === "kvadrat") svg.append(el("rect", { x: 30, y: 30, width: 140, height: 140, rx: 24, fill: c }));
  else svg.append(el("polygon", { points: "100,25 175,100 100,175 25,100", fill: c }));

  const letters = el("text", { x: 100, y: 116, "text-anchor": "middle", "font-size": 46, "font-weight": "bold",
                               "font-family": fontField.value, fill: "#fff" });
  letters.textContent = initials(nameField.value);
  svg.append(letters);

  // the name and the slogan (right)
  // the font size gets smaller for a longer name, so that it fits into the remaining ~200 units of width
  const size = Math.min(34, Math.floor(200 / (0.6 * Math.max(nameField.value.length, 1))));
  const title = el("text", { x: 195, y: sloganField.value ? 100 : 112, "font-size": size, "font-weight": "bold",
                             "font-family": fontField.value, fill: "#222" });
  title.textContent = nameField.value || "Logo";
  svg.append(title);
  if (sloganField.value) {
    const s = el("text", { x: 197, y: 132, "font-family": fontField.value, fill: c,
                           "font-size": Math.min(18, Math.floor(200 / (0.55 * sloganField.value.length))) });
    s.textContent = sloganField.value;
    svg.append(s);
  }

  preview.replaceChildren(svg);   // replace the old logo with the new one
}

// 3. every change in any field immediately draws the logo again
for (const f of fields) f.addEventListener("input", draw);
draw();
IdeaWhere in the code
the name from the home page arrives in the address (?naziv=...) and is read with URLSearchParamsstep 1
SVG elements are created with createElementNS (the ordinary createElement does not work for SVG)the function el
the whole look depends on the values of the fields – the function draw builds the logo from scratch every timestep 2
the input event on all fields → the logo changes while you type or choose a colourstep 3
text is inserted with textContent – safe (the lesson DOM and events)letters, title, s

Downloading the image: SVG and PNG

// 4. downloading
function fileName(extension) {
  return (nameField.value.trim() || "logo").toLowerCase().replace(/[^a-z0-9]+/g, "_") + "." + extension;
}

function download(url, name) {               // a temporary link that we "click" from the code
  const a = document.createElement("a");
  a.href = url;
  a.download = name;
  a.click();
}

function svgText() {
  return new XMLSerializer().serializeToString(document.getElementById("logo"));
}

document.getElementById("preuzmiSvg").addEventListener("click", () => {
  const blob = new Blob([svgText()], { type: "image/svg+xml" });
  const url = URL.createObjectURL(blob);
  download(url, fileName("svg"));
  URL.revokeObjectURL(url);
});

document.getElementById("preuzmiPng").addEventListener("click", () => {
  const image = new Image();
  image.onload = () => {
    const canvas = document.createElement("canvas");   // SVG -> drawing on a canvas -> PNG
    canvas.width = 800;
    canvas.height = 400;
    const ctx = canvas.getContext("2d");
    ctx.fillStyle = "#fff";
    ctx.fillRect(0, 0, 800, 400);
    ctx.drawImage(image, 0, 0, 800, 400);
    download(canvas.toDataURL("image/png"), fileName("png"));
  };
  image.src = "data:image/svg+xml;charset=utf-8," + encodeURIComponent(svgText());
});
FormatHow it is madeWhen
SVGthe text of the SVG element (XMLSerializer) → Blob (a file in memory) → a link with the download attributefor printing and large formats – sharp at every size
PNGthe SVG is loaded as an image, drawn on a canvas of double size and turned into PNGfor a profile picture, documents, social networks

The file name is made from the name: lower case letters, and everything that is not a letter or a digit becomes _ ("Pupin Club" → pupin_club.png).

Try the generator

The whole generator (HTML + JavaScript) works in the frame below. Change the name, the slogan, the colour, the shape and the font. Downloading is turned off in this frame for security reasons – it works when you open the page as your own file.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Generator – Logo Creator</title>
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css">
  <link rel="stylesheet" href="css/main.css">
</head>
<body class="bg-light">
  <div class="container py-4">
    <h1 class="h3 mb-4"><a href="naslovna.html" class="text-decoration-none">Logo Creator</a> · generator</h1>
    <div class="row g-4">
      <!-- left: the choices -->
      <form id="forma" class="col-md-5">
        <div class="mb-3">
          <label for="naziv" class="form-label">Name</label>
          <input id="naziv" class="form-control" maxlength="20" value="Logo">
        </div>
        <div class="mb-3">
          <label for="slogan" class="form-label">Slogan (optional)</label>
          <input id="slogan" class="form-control" maxlength="30">
        </div>
        <div class="row g-2 mb-3">
          <div class="col">
            <label for="boja" class="form-label">Colour</label>
            <input id="boja" type="color" class="form-control form-control-color w-100" value="#dd0022">
          </div>
          <div class="col">
            <label for="oblik" class="form-label">Shape</label>
            <select id="oblik" class="form-select">
              <option value="krug">circle</option>
              <option value="kvadrat">square</option>
              <option value="romb">diamond</option>
            </select>
          </div>
        </div>
        <div class="mb-3">
          <label for="font" class="form-label">Font</label>
          <select id="font" class="form-select">
            <option value="Arial, sans-serif">Arial</option>
            <option value="Georgia, serif">Georgia</option>
            <option value="'Courier New', monospace">Courier New</option>
          </select>
        </div>
        <button type="button" id="preuzmiSvg" class="btn btn-danger">Download SVG</button>
        <button type="button" id="preuzmiPng" class="btn btn-outline-danger">Download PNG</button>
      </form>
      <!-- right: the live preview -->
      <div class="col-md-7 text-center">
        <div id="prikaz" class="p-3 bg-white rounded shadow-sm"></div>
      </div>
    </div>
  </div>
  <script>
// ===== js/generator.js – Logo Creator =====
const NS = "http://www.w3.org/2000/svg";       // SVG elements are created with this "namespace"
const fields = ["naziv", "slogan", "boja", "oblik", "font"].map(id => document.getElementById(id));
const [nameField, sloganField, colorField, shapeField, fontField] = fields;
const preview = document.getElementById("prikaz");

// 1. the name from the address: generator.html?naziv=Pupin+Club (sent by the form on the home page)
const fromAddress = new URLSearchParams(location.search).get("naziv");
if (fromAddress) nameField.value = fromAddress.slice(0, 20);

// helper function: create an SVG element with attributes
function el(name, attributes) {
  const e = document.createElementNS(NS, name);
  for (const [k, v] of Object.entries(attributes)) e.setAttribute(k, v);
  return e;
}

// initials: "Pupin Club" -> "PC", "Logo" -> "LO"
function initials(text) {
  const words = text.trim().split(/\s+/).filter(w => w.length > 0);
  if (words.length === 0) return "?";
  if (words.length === 1) return words[0].slice(0, 2).toUpperCase();
  return (words[0][0] + words[1][0]).toUpperCase();
}

// 2. draw the logo from the current values of the fields
function draw() {
  const svg = el("svg", { xmlns: NS, viewBox: "0 0 400 200", width: "100%" });
  svg.id = "logo";
  const c = colorField.value;

  // the sign (left)
  if (shapeField.value === "krug") svg.append(el("circle", { cx: 100, cy: 100, r: 70, fill: c }));
  else if (shapeField.value === "kvadrat") svg.append(el("rect", { x: 30, y: 30, width: 140, height: 140, rx: 24, fill: c }));
  else svg.append(el("polygon", { points: "100,25 175,100 100,175 25,100", fill: c }));

  const letters = el("text", { x: 100, y: 116, "text-anchor": "middle", "font-size": 46, "font-weight": "bold",
                               "font-family": fontField.value, fill: "#fff" });
  letters.textContent = initials(nameField.value);
  svg.append(letters);

  // the name and the slogan (right)
  // the font size gets smaller for a longer name, so that it fits into the remaining ~200 units of width
  const size = Math.min(34, Math.floor(200 / (0.6 * Math.max(nameField.value.length, 1))));
  const title = el("text", { x: 195, y: sloganField.value ? 100 : 112, "font-size": size, "font-weight": "bold",
                             "font-family": fontField.value, fill: "#222" });
  title.textContent = nameField.value || "Logo";
  svg.append(title);
  if (sloganField.value) {
    const s = el("text", { x: 197, y: 132, "font-family": fontField.value, fill: c,
                           "font-size": Math.min(18, Math.floor(200 / (0.55 * sloganField.value.length))) });
    s.textContent = sloganField.value;
    svg.append(s);
  }

  preview.replaceChildren(svg);   // replace the old logo with the new one
}

// 3. every change in any field immediately draws the logo again
for (const f of fields) f.addEventListener("input", draw);
draw();

// 4. downloading
function fileName(extension) {
  return (nameField.value.trim() || "logo").toLowerCase().replace(/[^a-z0-9]+/g, "_") + "." + extension;
}

function download(url, name) {               // a temporary link that we "click" from the code
  const a = document.createElement("a");
  a.href = url;
  a.download = name;
  a.click();
}

function svgText() {
  return new XMLSerializer().serializeToString(document.getElementById("logo"));
}

document.getElementById("preuzmiSvg").addEventListener("click", () => {
  const blob = new Blob([svgText()], { type: "image/svg+xml" });
  const url = URL.createObjectURL(blob);
  download(url, fileName("svg"));
  URL.revokeObjectURL(url);
});

document.getElementById("preuzmiPng").addEventListener("click", () => {
  const image = new Image();
  image.onload = () => {
    const canvas = document.createElement("canvas");   // SVG -> drawing on a canvas -> PNG
    canvas.width = 800;
    canvas.height = 400;
    const ctx = canvas.getContext("2d");
    ctx.fillStyle = "#fff";
    ctx.fillRect(0, 0, 800, 400);
    ctx.drawImage(image, 0, 0, 800, 400);
    download(canvas.toDataURL("image/png"), fileName("png"));
  };
  image.src = "data:image/svg+xml;charset=utf-8," + encodeURIComponent(svgText());
});
</script>
</body>
</html>

Result:

Practice tasks

Each task has an example, a hint and a solution. The solutions have been checked in the browser.

TASK 01Difficulty: medium

A new shape: a hexagon

Add the shape "hexagon" to the generator: a new option in the drop-down list and drawing a regular hexagon with its centre at (100, 100) and a radius of 72.

TASK 02Difficulty: easy

A "Surprise me" button

Add a button that chooses a random colour, shape and font and draws the logo again.

Common mistakes and tips
  • SVG elements are created with document.createElementNS("http://www.w3.org/2000/svg", ...) – with the ordinary createElement they are not shown.
  • In SVG the y axis grows downwards.
  • When JavaScript changes the value of a field, the input event does not happen – that is why draw() is called by hand after that.
  • The fonts in a downloaded SVG depend on the computer that opens it; for a fixed look use PNG.

Check your knowledge

Open the quiz

The logo generator

1. How does the generator find out the name typed on the home page?




2. Which method creates SVG elements in JavaScript?




3. Where is the point (0, 0) in SVG?




4. Why is the logo drawn again at every input event?