Sometimes due to slow internet, website images take a long time to load, in that case developers mainly use two things. One is to add a loading bar there. Second is to use placeholder images. ‌Placeholder images indicate to users that a new image will appear in this place.

So today we will learn how to create placeholder images using JavaScript. Here we generate images using JavaScript.

We use placeholder images for many reasons, like loading time, design testing, missing data, and slow networks.

If you are working on an offline project and your project needs default images, then this tutorial can be very useful for you. From today, you will not have to go to the browser to download images for testing. Create demo images with JavaScript.

Video Tutorial:

If you are interested to learn by watching a video tutorial rather than reading this blog post you can watch the video down below.

HTML:

Let's start with the HTML code. We will create two tags. The first is the <img> tag. Inside the img tag, we will later dynamically insert the image using JavaScript.

And the second is the <a> tag, inside which we will insert the link to the generated image path. End the HTML code here.

<img id="placeholder" src="#"/>
<a id="image-path" href="#"></a>

StyleSheet (CSS):

Here we use a small stylesheet for the <a> tag. Using the overflow-wrap property in CSS, we will break the link inside the image tag. So that it does not go outside the body.

a {
	overflow-wrap: break-word;
}

JavaScript:

Now we come to the main topic. First we create a function, this function will return the image path.

We have named the function create_image_path. The parameters that we will give to the function are image size, text, options.

function create_image_path(size, text, options = {}) {
Default object:

Now we set the default values for generating the image. These can be customized with the help of object parameters.

The function will get the size of the image of an array in the parameter. From there, we will separate the height and width.

const {
    fontFamily = "Arial",
    fontSize = 40,
    textColor = "#000000",
    backgroundColor = "#E0E0E0",
    imageFormat = "image/png",
    jpegQuality = 0.9
} = options;

const [width, height] = size;

Create a canvas:

The next step is to create a canvas.

const canvas = document.createElement('canvas');
canvas.width = width;
canvas.height = height;
const ctx = canvas.getContext('2d');
Set background color:

That if the option parameter does not have a background color, then the default background color will become the background color of the canvas.

ctx.fillStyle = backgroundColor;
ctx.fillRect(0, 0, width, height);
Set text properties:

Here the size and font family of the text inside the canvas will be added. All the properties of the text will be added here.

ctx.font = `${fontSize}px ${fontFamily}`;
ctx.fillStyle = textColor;
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
Measure text to center it:

Used to find the measurement of text written on the canvas.

const textMetrics = ctx.measureText(text);
const textWidth = textMetrics.width;
const textHeight = fontSize;
Calculate position to center the text:

We must know the value of the canvas center position in order to position the text there.

const x = width / 2;
const y = height / 2;

ctx.fillText(text, x, y);
Return the Data URL:

So far the canvas has been created. Now we are converting the canvas to image format. Here we are checking if the image quality is given, then the path of the image will be returned in that image format.

if (imageFormat === "image/jpeg") {
    return canvas.toDataURL(imageFormat, jpegQuality);
} else {
    return canvas.toDataURL(imageFormat);
}

We have dynamically loaded the image and the path of the image in all the HTML that we created.

imagePath = create_image_path([200,200], "Hello..");

document.querySelector("#placeholder").src = imagePath;
document.querySelector("#image-path").innerText = imagePath;
document.querySelector("#image-path").href = imagePath;
Full Script:

We have shown all the code together here, you can copy and implement it in your project.

function create_image_path(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 textMetrics = ctx.measureText(text);
    const textWidth = textMetrics.width;
    const textHeight = fontSize;
    const x = width / 2;
    const y = height / 2;
    ctx.fillText(text, x, y);
    if (imageFormat === "image/jpeg") {
        return canvas.toDataURL(imageFormat, jpegQuality);
    } else {
        return canvas.toDataURL(imageFormat);
    }
}
imagePath = create_image_path([200,200], "Hello..");
document.querySelector("#placeholder").src = imagePath;
document.querySelector("#image-path").innerText = imagePath;
document.querySelector("#image-path").href = imagePath;

I hope you guys enjoyed this tutorial. If you have any suggestions and feedback to let me know through the comments below. Also to stay updated with the latest tutorial subscribe to me on Youtube.

Post a Comment

أحدث أقدم