{}const=>[]async()letfn</>var
JSWebDevelopment

How to create an AI image generator using HTML, CSS, and JavaScript

Learn how to create an AI image generator using only HTML, CSS, and JavaScript. Instructions for beginners, clear code, connection to the Hugging Face API and stylish design with a dark theme!

К

Kodik

Author

10 min read

How to create an AI image generator from scratch? 🤔

Let's figure out step by step how to build your own web application that will turn a text description into images using the Hugging Face API. All you need is a little knowledge of HTML, CSS, and JavaScript. This is a great project for beginners: easy to implement and giving an impressive result!

You can download all the code projects at the end of the article


📚 Contents

  • 🚀 Why do such a project?

  • 🛠️ What are we going to do?

  • 📁 Project structure

  • 1️⃣ HTML (index.html)

  • 2️⃣ CSS (style.css)

  • 3️⃣ JavaScript (script.js)

  • 💡 Result

  • 📌 Tips and ideas for improvement

  • 🙋 Frequently Asked Questions (FAQ)

  • ✅ Conclusion


🔥 100,000+ students already with us

Tired of reading theory?
Time to code!

Kodik — an app where you learn to code through practice. AI mentor, interactive lessons, real projects.

🤖 AI 24/7
🎓 Certificates
💰 Free
🚀 Start learning
Joined today

🚀 Why do such a project?

Imagine creating a web application that turns text into images using artificial intelligence in just a couple of hours. Sounds like magic? It's just a combination of HTML, CSS, JavaScript, and an external API. 🤖✨

That's why this project is a real find for a beginner:

  • Practice with API — you will learn how to send requests to an external server and process responses. This is a key skill of a modern web developer!

  • Cool visual - the result of your work will be immediately visible. You enter the text and get a bright image. It is very exciting and inspiring.

  • Knowledge consolidation — HTML, CSS, JS — all in one place. And not in abstract examples, but in this mini-application.

  • Light and dark theme - trend of recent years. We will make a toggle button between them - and you will learn how it is implemented in practice.

  • Portfolio — such a project will definitely not go unnoticed. It shows that you know how to work with the API, create interfaces and think about the user.

If you were looking for a project that is useful, beautiful, and really interesting, you have found it.


🛠️ What are we going to do?

Let's imagine: you open a page, enter a phrase like "castle on clouds during sunset", press a button — and in a couple of seconds you get unique images created by AI. This is exactly what we will be implementing!

We will create a full-fledged web application in which the user will be able to:

  • Enter a text description (prompt) describing an imaginary scene

  • Choose an image generation model (e.g., Stable Diffusion)

  • Adjust the number of images from one to four

  • Set the desired aspect ratio: square, horizontal or vertical

  • Press the "Generate" button and instantly see the result

  • Save images to your computer 💾

And also switch the theme between light and dark. Convenient, modern and beautiful.

This project will help you master real web development skills and understand how modern AI tools work.


📁 Project structure

Before writing the code, you need to organize the project correctly. This is an important step: a clear structure will help you navigate and make changes more easily in the future.

Create a separate folder and name it, for example, ai-image-generator. Inside this folder, create 3 main files:

  • index.html — the main markup will be here: page structure, buttons, input fields, and drop-down lists

  • style.css — a file with styles, in which we will make a modern and adaptive design, as well as implement a dark and light theme

  • script.js — JavaScript file that is responsible for logic: data processing, API connection, image generation, and interface interaction

Everything is simple and clear. In a few minutes you will have a base with which you can start creating!


1️⃣ HTML (index.html)

Let's start with the most important thing — the framework of our application. HTML is responsible for the structure of the page: how everything looks, where the buttons, fields, and headings are located. Here we will describe what the user will see in the browser.

HTML is the basis on which styles (CSS) and logic (JavaScript) are then “put on”.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>AI Image Generator Kodik APP</title>
  <!-- Font Awesome for icons -->
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" />
  <link rel="stylesheet" href="style.css" />
</head>
<body>
<div class="container">
  <!-- Header -->
  <header class="header">
    <div class="logo-wrapper">
      <div class="logo">
        <i class="fa-solid fa-wand-magic-sparkles"></i>
      </div>
      <h1>AI Image Generator</h1>
    </div>
    <button class="theme-toggle">
      <i class="fa-solid fa-moon"></i>
    </button>
  </header>
  <div class="main-content">
    <form action="#" class="prompt-form">
      <!-- Prompt Textarea Container -->
      <div class="prompt-container">
        <textarea class="prompt-input" placeholder="Describe your imagination in detail..." spellcheck="false" autofocus required></textarea>
        <button type="button" class="prompt-btn" title="Get Random Prompt">
          <i class="fa-solid fa-dice"></i>
        </button>
      </div>
      <!-- Prompt Actions / Buttons -->
      <div class="prompt-actions">
        <div class="select-wrapper">
          <select class="custom-select" id="model-select" required>
            <option value="" selected disabled>Select Model</option>
            <option value="black-forest-labs/FLUX.1-dev">FLUX.1-dev</option>
            <option value="black-forest-labs/FLUX.1-schnell">FLUX.1-schnell</option>
            <option value="stabilityai/stable-diffusion-xl-base-1.0">Stable Diffusion XL</option>
            <option value="runwayml/stable-diffusion-v1-5">Stable Diffusion v1.5</option>
            <option value="stabilityai/stable-diffusion-3-medium-diffusers">Stable Diffusion 3</option>
          </select>
        </div>
        <div class="select-wrapper">
          <select class="custom-select" id="count-select" required>
            <option value="" selected disabled>Image Count</option>
            <option value="1">1 Image</option>
            <option value="2">2 Images</option>
            <option value="3">3 Images</option>
            <option value="4">4 Images</option>
          </select>
        </div>
        <div class="select-wrapper">
          <select class="custom-select" id="ratio-select" required>
            <option value="" selected disabled>Aspect Ratio</option>
            <option value="1/1">Square (1:1)</option>
            <option value="16/9">Landscape (16:9)</option>
            <option value="9/16">Portrait (9:16)</option>
          </select>
        </div>
        <button type="submit" class="generate-btn">
          <i class="fa-solid fa-wand-sparkles"></i>
          Generate
        </button>
      </div>
    </form>
    <!-- Result Gallery Grid -->
    <div class="gallery-grid"></div>
  </div>
</div>
<script src="script.js"></script>
</body>
</html>

2️⃣ CSS (style.css)

Now that we have the structure, it's time to make the app really beautiful and pleasing to the eye. CSS is responsible for the appearance of all elements: from buttons to the background.

In our case, we will create a modern design with:

  • Smooth animations

  • Adaptive layout to make everything look good on both the computer and the phone

  • Light and dark theme, between which the user can switch in one click

  • Stylish buttons, input fields, and image cards

We will also connect the font Inter with Google Fonts — it looks modern and readable.

Such an interface is pleasant to use, and it is in no way inferior to externally ready-made services on the Internet!

/* Importing Google Fonts - Inter */
@import url('https://fonts.googleapis.com/css2?family=Inter:opsz,wght@14..32,100..900&display=swap');
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: "Inter", sans-serif;
}
:root {
  --color-primary: #5C56E1;
  --color-primary-dark: #5b21b6;
  --color-accent: #8B5CF6;
  --color-card: #FFFFFF;
  --color-input: #F1F1FF;
  --color-text: #09090E;
  --color-placeholder: #5C5A87;
  --color-border: #D4D4ED;
  --color-gradient: linear-gradient(135deg, #5C56E1, #8B5CF6);
}
body.dark-theme {
  --color-card: #1E293B;
  --color-input: #141B2D;
  --color-text: #F3F4F6;
  --color-placeholder: #A3B6DC;
  --color-border: #334155;
  background: var(--color-card);
  background-image: radial-gradient(circle at 15% 50%, rgba(99, 102, 241, 0.15) 0%, transparent 35%), radial-gradient(circle at 85% 30%, rgba(139, 92, 246, 0.15) 0%, transparent 35%), radial-gradient(circle at 50% 80%, rgba(99, 102, 241, 0.1) 0%, transparent 40%);
}

(The full code can be found on github. The link is at the end of the article - just paste it into style.css)


3️⃣ JavaScript (script.js)

HTML is responsible for the structure, CSS for the appearance, but JavaScript will breathe real life into our application.

With its help, we:

  • We process the user input — text description, selected model and generation parameters

  • We will send a request to the Hugging Face API to get images

  • Display images in a beautiful grid with loading effects

  • We will add the functionality of the "random hint" button, which automatically introduces interesting ideas

  • Implementing switching between light and dark themes

Here you will work with DOM, events, asynchronous requests (fetch), and much more. This is a great training for developing real JavaScript development skills!

👉 Insert your Hugging Face API key instead of PASTE-YOUR-API-KEY:

const promptForm = document.querySelector(".prompt-form");
const themeToggle = document.querySelector(".theme-toggle");
const promptBtn = document.querySelector(".prompt-btn");
const promptInput = document.querySelector(".prompt-input");
const generateBtn = document.querySelector(".generate-btn");
const galleryGrid = document.querySelector(".gallery-grid");
const modelSelect = document.getElementById("model-select");
const countSelect = document.getElementById("count-select");
const ratioSelect = document.getElementById("ratio-select");

const API_KEY = "PASTE-YOUR-API-KEY"; // Hugging Face API Key

// Example prompts
const examplePrompts = [
  "A magic forest with glowing plants and fairy homes among giant mushrooms",
  "An old steampunk airship floating through golden clouds at sunset",
  "A future Mars colony with glass domes and gardens against red mountains",
  "A dragon sleeping on gold coins in a crystal cave",
  "An underwater kingdom with merpeople and glowing coral buildings",
  "A floating island with waterfalls pouring into clouds below",
  "A witch's cottage in fall with magic herbs in the garden",
  "A robot painting in a sunny studio with art supplies around it",
  "A magical library with floating glowing books and spiral staircases",
  "A Japanese shrine during cherry blossom season with lanterns and misty mountains",
  "A cosmic beach with glowing sand and an aurora in the night sky",
  "A medieval marketplace with colorful tents and street performers",
  "A cyberpunk city with neon signs and flying cars at night",
  "A peaceful bamboo forest with a hidden ancient temple",
  "A giant turtle carrying a village on its back in the ocean",
];

If you don't have a key, register for free at huggingface.co and get it in the Access Tokens section

(The full code can be found on github. Link at the end of the article)


💡 Result

When you complete this project, you will have not just a set of files, but a real mini-application that looks professional and works with real artificial intelligence.

You will be able to:

  • Enter any imaginary description and get a generated image, as if from fantasy

  • Use different models for generation, including popular versions of Stable Diffusion

  • Save your favorite pictures and share them with friends

  • Switch the theme, depending on the time of day or mood 🌞🌙

And most importantly, you did it yourself. From the beginning to the end. Such a result gives a powerful boost of self-confidence and motivation to move on!


📌 Tips and ideas for improvement

The project is ready, but you don't have to stop there. Here's how you can level it up further:

  • Favorites - make it possible to add the best images to a separate gallery

  • Editing requests — add a re-generation button where you can change the prompt without a complete reload of the form

  • History — save previous queries and images in localStorage so that the user can return to them later

  • Feedback — allow the user to evaluate the result or leave a comment

  • Share - add the ability to share an image via a link or export it to social networks

This is a great way to develop a project and at the same time improve your skills!


🙋 Frequently Asked Questions (FAQ)

🔑 Where can I get a Hugging Face API key?

Go to the website huggingface.co, create an account (if you don't have one yet), then go to the section Settings > Access Tokens and generate a new key. Insert it into the variable API_KEY in script.js.

🖼️ How many images can be generated at a time?

You can choose from 1 to 4 images. This value is configured in the drop-down list on the page.

⚠️ Why isn't the image loading?

Possible reasons:

  • Invalid API key

  • Unstable internet connection

  • Error on the model side (you can see the details in the browser console logs)

🌗 How does theme switching work?

The site remembers the selected theme (light or dark) and saves it in localStorage, and also takes into account the system settings of the browser.

📱 Does it work on mobile?

Yes, the interface is adapted for mobile devices. All elements are scaled, and the image gallery is rearranged to fit the screen.

📤 Can I share the results?

Of course! Click on the download icon under the image - the file will be saved, and you can send it to friends or publish it on social networks.


✅ Conclusion

That's it — you've just gone from an empty folder to a ready-made AI app that generates images from text. 🔥

You figured out how to:

  • use HTML to build the interface

  • apply CSS to create a responsive and modern design

  • enable JavaScript and interact with an external API

This project is not just a training one. It looks decent, works stably and shows that you know how to build real web tools.

Keep experimenting:

  • try new models

  • change the interface

  • add new features

Each improvement will make you stronger as a developer. Good luck on your journey! 🚀

You can download the source code from our GitHub

🎯Stop procrastinating

Liked the article?
Time to practice!

In Kodik, you don't just read — you write code immediately. Theory + practice = real skills.

Instant practice
🧠AI explains code
🏆Certificate

No registration • No card