ArticleZip > Invert Colors Of An Image In Css Or Javascript

Invert Colors Of An Image In Css Or Javascript

Have you ever needed to invert the colors of an image on a website? It might sound like a complex task, but fear not! Whether you are working with CSS or Javascript, there are straightforward ways to achieve this effect. Let's dive right into how you can invert colors of an image using CSS or Javascript.

First, let's talk about inverting colors using CSS. To achieve this effect, you can use the filter property in CSS. Here's a simple example of how you can invert the colors of an image using CSS:

Css

.image {
    filter: invert(100%);
}

In this code snippet, we target the image element with the class "image" and apply the CSS filter property with the invert function set to 100%, which will invert all the colors of the image.

If you want to control the degree of inversion, you can adjust the percentage value. For example, a value of 50% would result in a partially inverted image, creating a unique visual effect.

Now, let's explore how you can achieve the same effect using Javascript. If you prefer a dynamic approach or need more control over the inversion process, Javascript can be a powerful tool. Here's a simple Javascript function that allows you to invert the colors of an image:

Javascript

function invertColors(imageElement) {
    const canvas = document.createElement('canvas');
    const ctx = canvas.getContext('2d');
    
    canvas.width = imageElement.width;
    canvas.height = imageElement.height;
    
    ctx.drawImage(imageElement, 0, 0);
    
    const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
    const data = imageData.data;
    
    for (let i = 0; i < data.length; i += 4) {
        data[i] = 255 - data[i];
        data[i + 1] = 255 - data[i + 1];
        data[i + 2] = 255 - data[i + 2];
    }
    
    ctx.putImageData(imageData, 0, 0);
    
    imageElement.src = canvas.toDataURL();
}

// Usage
const img = document.querySelector('.image');
invertColors(img);

In this Javascript function, we create a canvas element, draw the image on the canvas, manipulate the image data to invert the colors, and then update the image element with the inverted image using the toDataURL method.

By using this Javascript function, you have more flexibility and customization options when inverting colors, making it a great choice for more advanced scenarios.

Whether you choose CSS or Javascript to invert the colors of an image on your website, you now have the knowledge to implement this captivating visual effect. Experiment with different settings and have fun creating unique and eye-catching designs on your web projects!

×