How to find an average color of an image using JavaScript ? - GeeksforGeeks

14 Feb, 2022
The average color of an image can be found with JavaScript by drawing the image on a canvas element. The following steps have to be performed to get the average color of an image:
1. The image is first drawn on the canvas using the method context.drawImage() of the Canvas 2D API. This method takes in the image and the dimensions as parameters and draws it to the canvas.
Syntax:
context.drawImage( img, width, height );
2. The image data of the canvas is returned using the context.getImageData() method. It returns an ImageData object representing the pixel data for a specified section of the canvas. 
Syntax:
context.getImageData( x, y, width, height )
3. The average red, green and blue colors are then calculated with this image data by adding all the color values separately and finding the average value of that color.
Example:
html
<!DOCTYPE html><html lang="en"> <head>    <title>        Find Average Color of        image via JavaScript?    </title>     <style>        #img {            position: absolute;            top: 20%;            left: 25%;        }         #block {            position: absolute;            background-color: white;            height: 70px;            width: 70px;            left: 50%;            top: 25%;        }    </style></head> <body>    <img height="100px" width="150px"        id="img" src=        "image_to_find_average_color.png">     <div id="block"></div>     <!-- Function to find the average color -->    <script>        function averageColor(imageElement) {             // Create the canvas element            var canvas                = document.createElement('canvas'),                 // Get the 2D context of the canvas                context                    = canvas.getContext &&                    canvas.getContext('2d'),                imgData, width, height,                length,                 // Define variables for storing                // the individual red, blue and                // green colors                rgb = { r: 0, g: 0, b: 0 },                 // Define variable for the                // total number of colors                count = 0;             // Set the height and width equal            // to that of the canvas and the image            height = canvas.height =                imageElement.naturalHeight ||                imageElement.offsetHeight ||                imageElement.height;            width = canvas.width =                imageElement.naturalWidth ||                imageElement.offsetWidth ||                imageElement.width;             // Draw the image to the canvas            context.drawImage(imageElement, 0, 0);             // Get the data of the image            imgData = context.getImageData(                        0, 0, width, height);             // Get the length of image data object            length = imgData.data.length;             for (var i = 0; i < length; i += 4) {                 // Sum all values of red colour                rgb.r += imgData.data[i];                 // Sum all values of green colour                rgb.g += imgData.data[i + 1];                 // Sum all values of blue colour                rgb.b += imgData.data[i + 2];                 // Increment the total number of                // values of rgb colours                count++;            }             // Find the average of red            rgb.r                = Math.floor(rgb.r / count);             // Find the average of green            rgb.g                = Math.floor(rgb.g / count);             // Find the average of blue            rgb.b                = Math.floor(rgb.b / count);             return rgb;        }         // Function to set the background        // color of the second div as        // calculated average color of image        var rgb;         setTimeout(() => {            rgb = averageColor(                document.getElementById('img'));             // Select the element and set its            // background color            document                .getElementById("block")                .style.backgroundColor =                'rgb(' + rgb.r + ','                + rgb.g + ','                + rgb.b + ')';        }, 500)    </script></body> </html>
Output:
varshagumber28
CSS-Misc
HTML-Misc
JavaScript-Misc
Picked
CSS
HTML
JavaScript
Web Technologies
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Design a web page using HTML and CSS
Form validation using jQuery
How to set space between the flexbox ?
Search Bar using HTML, CSS and JavaScript
How to Create Time-Table schedule using HTML ?
How to set the default value for an HTML <select> element ?
How to set input type date in dd-mm-yyyy format using HTML ?
Hide or show elements in HTML using display property
How to Insert Form Data into Database using PHP ?
REST API (Introduction)