Now almost everyone is addicted to shorts or reels. I am not left out of either 😁. I also waste about an hour every day watching reels. The point is that people's patience is now lessening. So if a website takes a long time to load, the user may feel annoyed. That's why developers use placeholder images.
If the image size is large or the internet speed is slow, a placeholder image is shown instead of the image. This lets the user know that new images are coming soon to that place.
This tutorial will teach you how to create a placeholder image path using JavaScript. You will implement advanced canvas drawing, learn to convert from canvas to image path, and create a polished user interface with HTML and CSS. Ultimately you will create a fully usable tool and learn techniques that you can use as placeholders for any web project.
This tutorial will cover all the topics:
- Generating images doesn't just require programming languages like Python or Java. This can also be done using JavaScript.
- The idea of canvas is a strategy to use in other projects.
- Learn how to design a flexible website that supports the placeholder service.
The Inspiration:
I requested Google Gemini to create portfolio using HTML, CSS, and JavaScript. In response I get the HTML structure. Opening it in the browser shows a placeholder version of the portfolio image.
The surprising thing here is the placeholder image. The image showed the first letter of my name. After reviewing the coding, I found out that it was a website called Placehold that generated the image for me. I didn't know about this website even after coding for five years. This website provides you with placeholder images, which means you can convert any text into an image of any size, any color, any text style.
Let me show you an example:
I want to create a link to an image with my name. My name is Hemanta, so I will write the URL like this: First, enter the website URL (https://placehold.co/), then specify the desired image size (1280x720), and finally add the text you want to appear inside the image ("Hemanta"). The full link is https://placehold.co/1280x720?text=Hemanta.
This site inspired me to create today's tutorial. So let us find out how you can create this type of website.
Prerequisites for today's tutorial:
Today's tutorial may seem strange at first to a non-developer. So you can start by creating basic HTML structures.
Here are all the things you need to know:
- Very basic understanding of HTML and CSS
- You will need a basic understanding of vanilla JavaScript, the canvas element, and DOM manipulation. But don't worry, I will try to explain everything to you in detail here.
- It is beneficial to have a code editor—for example, VS Code or Sublime Text 3.
What you will learn
- How does a website like Placehold work?
- How to create a placeholder generator tool?
- How to convert an HTML canvas to an image link?
How do placeholder websites work?
It depends on the server language support, meaning it can be done in many different ways. If the website server uses PHP or Python, this is very easy to do. But here I want to tell you about a JavaScript method so that you can also implement it on your website very easily.
Step 1: Image data collection
Creating communication options between the website and the user. First you need to know what kind of image the user wants to generate, which can be done with the help of URL parameters. A URL parameter is a "key=value" pair that comes after a question mark (?). And if there are multiple parameters, an ampersand (&) is used between them.
Suppose the user wants to generate a 512 by 512 size placeholder image. And the image will have the text "Hello" inside. The easiest way to send this data to the web server using parameters is https://www.example.com/?size=512x512&text=Hello.
The JavaScript URLSearchParams interface will collect data from these URL parameters.
// 1. Get the query string
const queryString = window.location.search; // Returns "?size=512x512&text=Hello"
// 2. Create a URLSearchParams object
const params = new URLSearchParams(queryString);
// 3. Access the parameter 'size' and 'text'
const size = params.get('size'); // Returns "512x512"
const text = params.get('size'); // Returns "Hello"
console.log(size); // Output: 512x512
console.log(text); // Output: Hello
Step 2: Generate the image
The image is now generated based on the user request. We will create a JavaScript imageGenerator() function based on the user's needs that generates an image. We will create this function in the next steps.
// Split width and height
const parts = size.split('x'); // Returns "[512, 512]"
const width = parts[0]; // Returns 512
const height = parts[0]; // Returns 512
// Generate image path
const imagePath = imageGenerate([width, height], text); // Returns data:image/png;base64,...
Last Step: Showing Output
Finally, the image is delivered to the user. The IMG or SVG element is used to display the image on the website.
document.querySelector("img").src = imagePath;
How to create a placeholder generator tool?
Now I will show you how to create a placeholder tool using HTML, CSS, and JavaScript. The main purpose is to show how the script will generate the image. So we will focus more on the script instead of making the tool attractive.
Let's take a look at how the tool works in the code editor. Clicking the "Run Code" button will show you the real purpose of this tutorial. You will understand what we are going to do.
Step 1: Set Up the Basic Structure
To create the tool, we first need to create the HTML structure. This includes a DOCTYPE declaration, defining Style and Script sections, and using meta tags.
Step 2: Create the Tool Structure
Let's start by creating an input element for the tool structure. The input element type is set to text, so the user can type anything. The text that the user provides in the input element will be set to the placeholder image.
Next, we will create a button element. Using this bottom element, the user will call the JavaScript function.
Finally, we will create an IMG element. With the help of the IMG element, the generated image will be displayed.
<input name="text" type="text">
<button>Generater</button>
<img src="">
Step 3: Styling the Tools
At the beginning of CSS, we will set the margins of all elements to 5 pixels. To provide margin, the elements are not sandwiched together..
* {
margin: 5px;
}
body {
display: flex;
align-items: center;
justify-content: center;
flex-direction: column;
min-height: 100vh;
}
Next, we will use the flexbox method for the document body. After using this method, all elements inside the document body will be centered. The first step is to make the document body a flex container. Once the document body is changed to a flex container, we can easily use the justify-content and align-items CSS properties. These two properties do the job of centering, but one thing to keep in mind is that you need to specify a height. So here we have set the height of the document body to 100VH.
Then the elements will move to the center, but they will be vertically aligned. So we used the CSS flex-direction: column; property to align the elements horizontally. To make the tool look more beautiful, you can use the padding and background colors.
Step 4: Create the Images Generator
Now let's come to the main functionality of JavaScript. First we will create an imageGenerate() function—this function will return the image path. The function will create the image path using the image size, text, and optional parameters.
function imageGenerate(size, text, options = {}) {
const {
fontFamily = "Arial",
fontSize = 40,
textColor = "#000000",
backgroundColor = "#E0E0E0",
imageFormat = "image/png",
jpegQuality = 0.9
} = options;
const [width, height] = size;
const canvas = document.createElement('canvas');
canvas.width = width;
canvas.height = height;
const ctx = canvas.getContext('2d');
ctx.fillStyle = backgroundColor;
ctx.fillRect(0, 0, width, height);
ctx.font = `${fontSize}px ${fontFamily}`;
ctx.fillStyle = textColor;
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
const x = width / 2;
const y = height / 2;
ctx.fillText(text, x, y);
return canvas.toDataURL(imageFormat);
}
Here's a breakdown of the main functionalities and their purposes:
Input Parameters:
function imageGenerate(size, text, options = {}) {
Default object:
Here are the default values for generating images. To customize these, include an object parameter in the function.
const {
fontFamily = "Arial",
fontSize = 40,
textColor = "#000000",
backgroundColor = "#E0E0E0",
imageFormat = "image/png",
jpegQuality = 0.9
} = options;
Here are the details of the default values.
fontFamily = "Arial":The style of the text inside the placeholder image.fontSize = 40:The default size of the placeholder image text will be 40 pixels.textColor = "#000000":By default, the text color is black (hex code #000000).backgroundColor = "#E0E0E0":This is used to change the background of the placeholder image. Because placeholders are generally gray, we use gray as the default background color.imageFormat = "image/png":Here you can set the image format. By default, the function will generate a PNG-format image.jpegQuality = 0.9:The quality of the placeholder image is determined.
Collecting the image size:
const [width, height] = size;
This function takes an image array as input, determines its size, and then separates the height and width values.
Creating the canvas:
const canvas = document.createElement('canvas');
canvas.width = width;
canvas.height = height;
const ctx = canvas.getContext('2d');
Here a new <canvas> element is created using document.createElement(). Then, its width and height are set based on the desired image dimensions.
Finally, the 2D rendering context is obtained with canvas.getContext('2d'), which allows drawing on the canvas.
Adding background color:
ctx.fillStyle = backgroundColor;
This is used to change the background color of the canvas. If no preferred background color is provided, it will set the default color.
Drawing Rectangle:
ctx.fillRect(0, 0, width, height);
Here, a rectangle is drawn on the canvas using fillRect(0,0,width,height). The first two values of fillRect() are set to 0, which will determine the position of the rectangle on the canvas.
It is used to create a rectangle across the entire canvas.
Styling the text:
ctx.font = `${fontSize}px ${fontFamily}`;
ctx.fillStyle = textColor;
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
Here are the methods for displaying text on canvas and their purpose.
- ctx.font: Sets the font size and style (default value is "40px Arial").
- ctx.fillStyle: Changes the fill color of the text.
- ctx.textAlign: Centers the text horizontally relative to the x-axis.
- ctx.textBaseline: And it centers the text vertically.
Calculating the center:
const x = width / 2;
const y = height / 2;
ctx.fillText(text, x, y);
Here, the width is divided by 2 to get the horizontal center value of the canvas. Similarly, halving the height reveals the vertical center position of the canvas.
Converting canvas to image:
It uses canvas.toDataURL(imageFormat) to convert the canvas content into a base64 data URI string.
return canvas.toDataURL(imageFormat);
Step 5: Show Image
var text = document.querySelector("input");
var button = document.querySelector("button");
var img = document.querySelector("img");
button.addEventListener("click", function(){
imagePath = imageGenerate([200,200], text.value);
img.src = imagePath;
});
Finally, we will call the imageGenerate() function. But the condition here is that the function will be called only when the user clicks the button. Then the imageGenerate() function returns the path to the image. And that path has been added to the source of the img element.
Thank you for reading the entire article. I hope you gained some insight into Placeholder Image Path Generator. For more content like this, you can follow me on YouTube.
Happy Coding!

0 Comments