Image Effects 3 Easy Ways to Eliminate Duplicate Images The Basics of Face Detection in Python How to Implement Multiple File Upload in PHP Like a Pro Creating Custom Image Cropping Interfaces in Android How to Create Simple Yet Effective PHP Overlay Understanding Real-Time Image Recognition How to add a shadow effect to an image with CSS How to crop an image in Flutter with Cloudinary How To Rotate an Image with Java Image Processing with Python Rotating an image with CSS Enhancing User Experience with a Responsive Image Slider Building a Python Image Recognition System Building an Interactive JavaScript Image Manipulation Tool Image Align Centering with HTML and CSS Efficient Image Cropping Techniques with Angular and Cloudinary Ultimate Guide to Photo Gallery on Android A Comprehensive Guide to Adding Text to Images on Android Mastering Background Changes in React Applications Comprehensive Guide on Changing Background on Android Devices Mastering Image Rotation in Java A Guide to Adding Text to Images with Python A Guide to Converting Images to Grayscale with Python Introduction Creating an Image Overlay with JavaScript Rotating an Image in Python Creating a Dynamic Photo Gallery with jQuery Creating An Interactive Photo Gallery Using JavaScript Mastering Overlay in Android Mastering Angular Overlay: A Comprehensive Guide Comprehensive Guide to Overlay in Flutter Mastering Overlay React for Responsive Design Solutions Create a Blurred Image with PHP: A Comprehensive Guide Guide to Using Blur Image in Flutter Mastering Blur Image in React Native Mastering Image Blurring in Python Mastering the Art of Image Blurring Mastering the Art of Image Blurring in Java The Ultimate Guide to Blurring Images on Android Understanding and Implementing Blur Image in JQuery An Extensive Walkthrough of Blurring Images with JavaScript How to Use HTML, CSS, and JavaScript to Make an Image Slider HTML Image Tag How to Crop GIFs? How to Align Images with CSS Ken Burns Effect – Complete Guide and How to Apply It Cartoonify – Complete Guide on Cartoonify Image Effect Mastering Web Aesthetics: A Comprehensive Guide to Gradient Fades Sepia Effect: The Ultimate Guide to the Sepia Photo Effect What is Vignette? Guide to Vignette Image Editing Pixelate – The Ultimate Guide to the Pixelation Effect How to Outline an Image: Enhancing Visual Appeal and Depth Make Your Photos Pop with Image Effects Upscale Image – Developers guide to AI-driven image upscaling Image Manipulation: History, Concepts and a Complete Guide A Full Guide to Object-aware Cropping Simplify Your Life with Automatic Image Tagging How To Resize Images In WordPress How To Create a Progress Bar For Asset Uploads Animated GIFs – What They Are And How To Create Them How To Automatically Improve Image Resolution AI Drop Shadow Get Image Dimensions From URLs Automatically Add Sepia Effect To Images Automatically Make an Image a Cartoon Automatically Add Blur Faces Effect To Images Automatically Add Background Removal Effect to an Image How to Resize an Image with React How to Easily Resize an Image with React Native

Creating an Image Overlay with JavaScript

image overlay javascript

An overlay or overlay effect is a visual element that allows you to add or obscure contextual information by adding an additional layer on top of another element (e.g., images and videos) in an interface. Overlays are especially useful in web design for adding informational elements like text, images, modals, popovers, tooltips, etc. They can also be used for censorship or privacy protection by blurring or masking out parts of a visual element (e.g., images and videos).

In this article, we’ll explore different methods of adding overlays to visual elements, particularly images, in JavaScript.

In this article:

Adding Overlays with CSS

Suppose we have the following product image:

image overlay javascript
Image attribution: Photo by Marcus Loke on Unsplash

And we want to layer the image tag below on top of it as a label:

image overlay javascript

Here’s how we would do that with HTML and CSS.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Overlay Example With HTML and CSS</title>
  <style>
    .photo {
      position: relative;
      width: 40%;
      max-height: 10%;
    }

    .overlay-content {
    position: absolute;
    top: 0;
    width: 100%;
    height: 100%;
    }

    .tag{
    position: absolute;
    right: 10px;
    }
  </style>
</head>
<body>

<div class="photo">
  <img src="clothes.jpg" width="100%" height="100%">
  <div class="overlay-content">
    <img class="tag" src="50-off.png" width="30%" height="20%">
  </div>
</div>

</body>
</html>

The above code gives us the following result:

image overlay javascript

Although the example above works as intended, most of the time, you want a more effective solution that offers you advanced configuration options and control over the labeling process.

image overlay javascript

Adding Overlays with Cloudinary

There are many possibilities to explore when it comes to applying overlays to visual elements in Cloudinary. With Cloudinary, you can layer any type of resource, such as images, icons, or text, on top of another visual element.

A layer is a type of transformation that allows us to add overlays to visual elements in Cloudinary. For example, applying an image layer directly to the URL of an image uploaded to Cloudinary has the following syntax:

https://res.cloudinary.com/your-cloudinary-name/image/upload/l_public_id_of_image_to_use_as_overlay/fl_layer_apply/base_image_to_add_overlay.jpg

Additionally, we can customize the layered asset by applying transformations and adjusting its placement (using placement qualifiers such as gravity, offset, and others) on the base image.

Using the same image from the previous example, let’s see how, in the following steps, we can use Cloudinary to add image overlays using the NodeJS SDK.

Step 1 – Setting up the Application

To get started, create a new directory for the application and run npm init in the folder to initialize a Node application. You’ll be taken through a few prompts to configure the application. The end result will look like something below:

image overlay javascript

Step 2 – Install Necessary Packages and Dependencies

Run the command below in the terminal to install the required dependencies for the project:

npm install express multer cloudinary
  • Express: A web application framework for Node.js designed for building web applications and APIs.
  • Multer: A middleware for handling multipart/form-data and uploading files in NodeJS applications.
  • Cloudinary: The Cloudinary NodeJS SDK provides an API for uploading, storing, transforming, and delivering media files.

Next, in the package.json file in the root directory, modify the scripts field to the following:

..."scripts": {    "dev": "node --watch --env-file=.env index.js" },

This tells Node to automatically restart the express server whenever we make changes to the index.js file and specify the file’s location that holds the environment variables.

Step 3 – Add Environment Variables

We need to use our Cloudinary API credentials to access Cloudinary programmatically with the Node.js SDK. Log in to your Cloudinary account and copy the values from the dashboard panel as shown below:

image overlay javascript

Cloudinary dashboard

Now, create a .env file in the root directory and add the corresponding values as follows:

CLOUDINARY_API_KEY =
CLOUDINARY_CLOUD_NAME =
CLOUDINARY_API_SECRET =

Step 4 – Writing the Code

First, we need to set up the express server and ensure it’s working. Create a file named index.js in the root directory and add the code below to it:

const express = require("express");
const app = express();

app.get("/", (req, res) => {
  res.send("Welcome to the homepage.");
});

app.listen(3000, () => {
  console.log("App is running!");

Next, start the server by running npm run dev. If everything goes well, you should see App is running logged to the console.

Next, modify the content of index.js to the following:

const express = require("express");
const multer = require("multer");
const path = require("node:path");
const fs = require("fs");
const cloudinary = require("cloudinary").v2;

cloudinary.config({
  cloud_name: process.env.CLOUDINARY_CLOUD_NAME,
  api_key: process.env.CLOUDINARY_API_KEY,
  api_secret: process.env.CLOUDINARY_API_SECRET,
  secure: true,
});

const app = express();

app.get("/", (req, res) => {
  res.send("Welcome to the homepage!");
});

// Function to check if the uploaded file is an image file
const fileFilter = (req, file, cb) => {
  const extname = path.extname(file.originalname).toLowerCase();
  if (extname === "jpg" || "jpeg" || "png" || "webpm" || "tiff" || "bmp") {
    return cb(null, true);
  }
  const error = new Error("Only image files are allowed!");
  error.status = 400;
  cb(error, false);
};

// Create a directory to upload the images on disk
var dir = "./uploads/";

if (!fs.existsSync(dir)) {
  fs.mkdirSync(dir);
}
const upload = multer({ dest: "uploads/", fileFilter });

// The overlay Cloudinary URL that will be updated later in the code
let overlayURL;

// Function to upload the image file to Cloudinary
const cloudinaryImageUpload = (file) => {
  return new Promise((resolve, reject) => {
    cloudinary.uploader
      .upload(file)
      .then((result) => {
        resolve(result.secure_url);
      })
      .catch((error) => {
        reject(error);
      });
  });
};

// Function to add the overlay to the base image
const addOverlayToImage = (img) => {
  return new Promise((resolve, reject) => {
    cloudinary.uploader
      .upload(img, {
        eager: [
          {
            overlay: { url: overlayURL },
            gravity: "north_east",
            x: "10",
            y: "10"
          },
        ],
      })
      .then((result) => {
        resolve(result.eager[0].secure_url);
      })
      .catch((error) => {
        reject(error);
      });
  });
};

// Endpoint to upload the image to use as overlay
app.post("/overlay", upload.single("image"), async function (req, res, next) {
  if (req.file !== undefined) {
    try {
      const overlay = await cloudinaryImageUpload(req.file.path);
      overlayURL = overlay;
      res.status(200).json({
        success: true,
        overlay: overlayURL
      });
    } catch (error) {
      res.status(400).json({
        success: false,
        error,
      });
    }
  } else {
    res.status(400).json({
      success: false,
      error: "No image file was uploaded",
    });
  }
});

// Endpoint to upload the base image file
app.post("/base", upload.single("image"), async function (req, res, next) {
  if (req.file !== undefined) {
    try {
      const baseImageWithOverlay = await addOverlayToImage(req.file.path);

      res.status(200).json({
        success: true,
        file: baseImageWithOverlay,
      });
    } catch (error) {
      res.status(400).json({
        success: false,
        error,
      });
    }
  } else {
    res.status(400).json({
      success: false,
      error: "No image file was uploaded",
    });
  }
});

app.listen(8080, () => {
  console.log("App is running!");
});

Here’s what is going on in the code above:

  • The /overlay endpoint is used to upload the image file to be used as an overlay.
  • The /base endpoint is used for uploading the base image file to which the overlay will be applied.
  • Next, the addOverlayToImage function uploads and applies the overlay to the image using the cloudinary.uploader.upload() method.
  • This example uses the eager transformation mode to apply the overlay transformation to the base image before it’s uploaded to Cloudinary.
  • The overlay parameter in the eager array specifies the URL of the overlay – which has already been uploaded to Cloudinary.
  • The gravity parameter sets the position in which the layer is placed within the base image. It is set to ‘center’ by default. You can use the interactive demo here to experiment with gravity and coordinate parameters.
  • The x and y parameters set the coordinates (or padding) of the overlay relative to the top-right corner as specified by the gravity parameter.

Step 5 – Trying it Out

For this step, we’ll make use of the Postman VS Code extension.

First, upload the overlay image to the /overlay endpoint. The result will be used to update the overlayURL variable that we defined in the code.

image overlay javascript

Next, we’ll upload the base image to the /base endpoint and obtain the URL of the image with the overlay applied to it, as shown in the Postman request below:

image overlay javascript

Here’s the output of the image link:

image overlay javascript

This example shows Cloudinary offers more powerful image processing capabilities than plain HTML and CSS. It allows you to dynamically manipulate images on the fly. Also, Cloudinary handles image storage and delivery for you, saving you the trouble of managing image assets manually.

Final Thoughts

Image overlays offer the opportunity to enhance the presentation of digital content by creating visual effects, adding branding elements, and emphasizing specific information.

In this article, we explored two methods of adding image overlays in JavaScript. We also explored how to use plain HTML, CSS, and Cloudinary. Feel free to sign up for a Cloudinary account today and experiment with the different options available for adding overlays to visual content.

Take your digital experience to the next level with Cloudinary’s powerful media optimization tools. Sign up for free today!

QUICK TIPS
Colby Fayock
Cloudinary Logo Colby Fayock

In my experience, here are tips that can help you better implement and optimize image overlays using JavaScript and Cloudinary:

  1. Use CSS blend modes for simple overlay effects
    If you only need basic overlay effects (e.g., tint, opacity changes), utilize CSS blend modes like mix-blend-mode and background-blend-mode. These modes offer flexible ways to layer images and colors without needing additional JavaScript code, improving performance and simplifying implementation.
  2. Apply dynamic overlays with Cloudinary’s URL-based transformations
    Take advantage of Cloudinary’s URL-based transformations for dynamic overlays, such as watermarks or brand logos. By appending parameters like l_overlay and fl_layer_apply directly in the image URL, you can instantly generate new versions of the image with different overlays, saving development time and reducing server-side processing.
  3. Leverage Cloudinary’s auto-gravity for accurate overlay positioning
    When applying overlays using Cloudinary, use gravity: "auto" to ensure that overlays are placed dynamically based on the content of the base image. This feature is especially useful when working with portraits or images containing multiple objects, ensuring overlays do not obscure critical visual information.
  4. Optimize overlay image quality to match base images
    If the base image is optimized with a specific quality setting, use q_auto for the overlay as well to maintain visual consistency. This ensures that both base and overlay images are delivered at the appropriate quality levels, preventing unexpected visual artifacts or misalignment between different image layers.
  5. Use SVG overlays for scalable and high-quality text overlays
    When adding text overlays, consider using SVG files instead of raster images for labels or watermarks. SVGs scale perfectly on high-resolution screens and retain clarity even when resized. With Cloudinary, you can use the overlay parameter to layer SVG files on top of the base image for high-quality, responsive results.
  6. Combine overlays with responsive image techniques
    When displaying overlayed images in responsive designs, combine Cloudinary’s responsive image transformations (e.g., dpr_auto, w_auto) to generate appropriately sized images based on the user’s device. This approach reduces bandwidth usage while ensuring that overlays appear correctly across various screen sizes.
  7. Implement lazy loading for overlayed images
    In JavaScript, use the IntersectionObserver API to implement lazy loading for images with overlays. This approach delays the loading of complex overlayed images until they are about to enter the viewport, improving initial page load times and reducing the number of simultaneous image requests.
  8. Handle complex transformations with Cloudinary’s chained transformations
    For advanced overlay scenarios (e.g., multiple text layers with different fonts, watermarks with transparency), use Cloudinary’s chained transformations. This feature allows you to apply multiple transformations sequentially (e.g., resize, crop, overlay, and text addition), reducing the need for manual post-processing.
  9. Use secure: true in Cloudinary configurations for HTTPS URLs
    Always set secure: true in Cloudinary’s JavaScript configuration to ensure that the generated image URLs use HTTPS. This setting prevents mixed content issues on modern browsers, enhancing security and ensuring that images with overlays are loaded correctly in secure contexts.
  10. Combine Cloudinary overlays with image analysis for automated labeling
    If your application deals with user-uploaded content, consider integrating Cloudinary’s auto_tagging or image analysis features to dynamically add overlays based on detected objects or content categories. This technique is powerful for automating watermark placements, content categorization, or contextual branding based on the subject matter of the image.

By applying these advanced techniques, you can maximize the effectiveness and efficiency of image overlays in your JavaScript projects, leveraging both CSS and Cloudinary’s robust image transformation capabilities.

Last updated: Oct 2, 2024