Now almost everyone is addicted to reels. I also waste time watching reels every day. Here, my point is that people losing their patience. If a website takes a long time to load, users feel annoyed. This is why developers use placeholder images.
You may sometimes see placeholder images due to slow internet. It keeps the user hooked, and doesn't let them lose patience.
This tutorial will teach you how to create a placeholder image using JavaScript. Here, you will apply advanced techniques for drawing on <canvas>. At the end, you will create a complete tool that converts from canvas to image path.
This tutorial will cover:
- It's possible to generate images using JavaScript.
- Techniques for using Canvas in necessary projects.
- How to support every website the placeholder service.
The Inspiration:
I want to give full credit for this tutorial to placehold.co. This amazing website inspired me to create today's tutorial.
How the placehold.co Website Works?
Suppose, I want to create a picture with my name. My name is Hemanta. I can generate a custom image by URL. I add the website URL, choose an image size like 1280x720, and then add my name. The URL looks like this:
https://placehold.co/1280x720?text=Hemanta
When I open this link in the browser, Placehold.co automatically creates an image with the text Hemanta in the center.
Prerequisites
Today's tutorial may seem a difficult for a beginner at first. So,you can start by creating basic HTML structures.
Here are all the things you need to know:
- Basic understanding of HTML, CSS, and JavaScript
- The canvas element, and DOM manipulation.
- Code editor, like VS Code or Sublime Text 3.
But don't worry, I will try to explain everything.
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