Search code examples
javascriptimagepixel

Javascript - Most repeats pixels on background-image


How to find the most repetitive pixel in the background-image and find out the color? Help!


Solution

  • You don't have access to the pixel data of a background image via JavaScript. What you will have to do is to create a new Image object and set the source to the background image URL. Afterwards, you will have to do these steps:

    • Create an in-memory canvas object
    • Draw the image on the canvas
    • Get the image data, iterate through all pixels and store the colors in an Object (key = color, value = amount of repitition)
    • Sort the array by the amount of repitition, then select the first value

    Here, I created an example. This loads the JSconf logo and sets the body's background color to the most repetitive color.

    // Create the image
    var image = new Image();
    image.crossOrigin = "Anonymous";
    
    image.onload = function () {
        var w = image.width, h = image.height;
    
        // Initialize the in-memory canvas
        var canvas = document.createElement("canvas");
        canvas.width = w;
        canvas.height = h;
    
        // Get the drawing context
        var context = canvas.getContext("2d");
    
        // Draw the image to (0,0)
        context.drawImage(image, 0, 0);
    
        // Get the context's image data
        var imageData = context.getImageData(0, 0, w, h).data;
    
        // Iterate over the pixels
        var colors = [];
        for(var x = 0; x < w; x++) {
            for(var y = 0; y < h; y++) {
                // Every pixel has 4 color values: r, g, b, a
                var index = ((y * w) + x) * 4;
    
                // Extract the colors
                var r = imageData[index];
                var g = imageData[index + 1];
                var b = imageData[index + 2];
    
                // Turn rgb into hex so we can use it as a key
                var hex = b | (g << 8) | (r << 16);
    
                if(!colors[hex]) {
                    colors[hex] = 1;
                } else {
                    colors[hex] ++;   
                }
            }
        }
    
        // Transform into a two-dimensional array so we can better sort it
        var _colors = [];
        for(var color in colors) {
            _colors.push([color, colors[color]]);   
        }
    
        // Sort the array
        _colors.sort(function (a, b) {
            return b[1] - a[1]; 
        });
    
        var dominantColorHex = parseInt(_colors[0][0]).toString(16);
        document.getElementsByTagName("body")[0].style.backgroundColor = "#" + dominantColorHex;
    };
    
    image.src = "http://upload.wikimedia.org/wikipedia/commons/thumb/6/6a/JavaScript-logo.png/600px-JavaScript-logo.png";