JavaScript: black and white inverted effect on images

JavaScript: black and white inverted effect on images

In this article, we'll walk you through the process of creating a JavaScript function that can be used to apply this effect to images on your website

Creating an inverted black and white effect on an image can add a unique creative touch to your web projects. In this article, we'll walk you through the process of creating a JavaScript function that can be used to apply this effect to images on your website.

Before diving into the code, it's important to understand what we mean by "inverted black and white effect". This effect converts a color or black-and-white image to its grayscale version, and then inverts the tones making the chiaroscuro opposites. Light areas become dark and vice versa, resulting in an image with distinctive visual contrast.

Start by inserting a canvas element into your HTML where the edited image will be displayed. You will also need to have a source image, which can be included directly in the HTML or loaded dynamically via JavaScript.

Use JavaScript to load the image into the canvas. This step is necessary to manipulate the pixels of the image.


const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
const img = document.getElementById('sourceImage');

img.onload = function() {
     canvas.width = img.width;
     canvas.height = img.height;
     ctx.drawImage(img, 0, 0);
     applyInvertBlackAndWhite();
};

The crucial part is the applyInvertBlackAndWhite function. Here, it reads the pixels of the image, converts them to grayscale and then inverts the colors.


function applyInvertBlackAndWhite() {
     const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
     const data = imageData.data;

     for (let i = 0; i < data.length; i += 4) {
         // Convert to grayscale
         const gray = data[i] * 0.3 + data[i + 1] * 0.59 + data[i + 2] * 0.11;
        
         // Invert colors
         data[i] = 255 - grey; // Red
         data[i + 1] = 255 - grey; // Green
         data[i + 2] = 255 - grey; // Blue
     }
    
     ctx.putImageData(imageData, 0, 0);
}

Conclusion

You have now successfully created a JavaScript function that applies an inverted black and white effect to your images. This effect not only adds an interesting visual element to your website, but can also be used to highlight certain graphic elements or create a particular atmosphere. Remember that playing with the pixels of an image offers endless creative possibilities, so don't hesitate to explore further and customize this effect to your needs.