Calculate the average color of the outer pixels in an image

I am looking to dynamically set the background color of a div using the average color of the outer pixels in an image. This way, I can avoid manually setting the background color for each image.

For example, if the image is 100px x 100px, I would check the 5 outer pixels at the top, right, left, and bottom of the image. This totals to 5 x 100 x 4 pixels. By calculating the average color of these pixels with JavaScript, I can then apply that color as the background color of the div.

So if the calculated average color is #000000, the div background will be #000000. Similarly, if the average color is #FAFAFA, the div background will be #FAFAFA.

Answer №1

To achieve this, the utilization of canvas is necessary. However, it is important to ensure that CORS restrictions are met.

The process involves extracting pixels from the specified region, totaling them up, and then dividing by the number of pixels counted.

Live Demonstration

var img = new Image();                            // Load an image
img.crossOrigin = "";                             // CORS requirement...
img.onload = function() {                         // When the image has finished loading:
  var div = document.querySelector("div");
  div.appendChild(this);                          // Add the image to the DOM for demonstration purposes 
  div.style.background = analyse(img, 5);         // Background color will be set based on the analysis result
}
img.src = "http://i.imgur.com/rUeQDjE.png";       // Link to the image (CORS enabled)

function analyse(img, border) {
  var canvas = document.createElement("canvas"),  // Create a canvas element
      ctx = canvas.getContext("2d"),              // Get the context
      w = img.naturalWidth,                       // Obtain actual width..
      h = img.naturalHeight;
  
  canvas.width = w;                               // Set canvas size
  canvas.height = h;
  
  ctx.drawImage(img, 0, 0);                       // Draw the image on the canvas
  
  // Perform checks:, for instance:
  //if (border*2 > canvas.width || border*2 > canvas.height) throw "Image too small!";
  
  // Extract borders, prevent overlaps (not crucial in this scenario):
  var top = ctx.getImageData(0, 0, w, border).data;
  var left = ctx.getImageData(0, border, border, h - border*2).data;
  var right = ctx.getImageData(w - border, border, border, h - border*2).data;
  var bottom = ctx.getImageData(0, h - border, w, border).data;
  
  var r = 0, g = 0, b = 0, cnt = 0;
  
  // Count pixels and sum up color components: (refer to function below)
  countBuffer(top);
  countBuffer(left);
  countBuffer(right);
  countBuffer(bottom);
  
  // Calculate average
  r = (r / cnt + 0.5)|0;
  g = (g / cnt + 0.5)|0;
  b = (b / cnt + 0.5)|0;
  
  return "rgb(" + r + "," + g + "," + b + ")";
  
  function countBuffer(data) {
    var i = 0, len = data.length;
    while(i < len) {
        r += data[i++];   // Add red component etc.
        g += data[i++];
        b += data[i++];
        i++;
        cnt++;            // Count one pixel
    }
  }
  
}
div {padding:30px}
<div></div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Having trouble with implementing jQuery fadeIn for thumbnail images inside a div?

I'm trying to create a functionality where clicking on a thumbnail image in a div will display the full-size version of that image in another div. I want to implement this using the jQuery fadeIn function, but my code isn't working and I am not v ...

The Bootstrap 4 grid appears to be malfunctioning as the columns are not displaying next to each other as expected

I've implemented the code below in an attempt to achieve the desired layout shown in the image, but instead, I'm getting a different outcome. Can someone help me figure out what I might be doing wrong with the Boostrap 4 grid system? I'm co ...

Failure to append an object to the array occurs when submitting an HTML form

I am facing an issue with a form that is supposed to add input values to an array as objects when submitted. However, every time I submit the form, the console briefly shows that there is an array with one object, only for it to disappear. Below is the f ...

Hide the menu when a menu link is selected

After conducting extensive research, I have come across several scripts that can achieve what I am trying to do. However, I am unsure of how to implement them with my particular WordPress theme. Therefore, I am seeking assistance here: The theme I am usin ...

"When the value is false, use the Vue binding to apply a specific

My challenge involves managing a website that is designed to receive boolean values and store them in an array where the key represents the ID and the value represents the boolean. For example: policiesActive[ "2" => false, "3" => false] The w ...

Having trouble retrieving text using getText() or getAttribute("innerHTML")

getAttribute but struggling to retrieve the text associated with each combobox. I need to access the text content of every combobox. <small> <input type="checkbox" checked="checked" value="on" name="irOperations[0]"/> Account Activity < ...

Is there an automatic bottom padding feature?

Currently, I am facing a challenge in fitting the loader into the container without it being overridden by the browser. Using padding-bottom is not an ideal solution as it results in the loader appearing un-resized and unprofessional. Any suggestions or co ...

Converting RSS title to HTML format with the help of JavaScript

I am currently working on populating a menu on a webpage with the 5 latest topics from our site's RSS newsfeed using JavaScript (specifically jQuery version 1.9.1). I have been searching for a solution, but most answers I find reference deprecated scr ...

Angular: facing difficulty displaying static html pages on server, although they render correctly when run locally

Within my Angular project, I have stored a few static html files (specifically sampleText.html) in the src/assets/html folder. In one of my components, I am attempting to fetch and display this file. The following code is being used for this purpose. Every ...

The mouseenter event in jQuery is failing to trigger

I'm encountering an issue with the mouseenter event on a div section of my webpage. I am attempting to alter the background color of this div when the mouse enters, but it seems to be disregarded. This is the basic HTML code: <div id="services" c ...

Tips for initializing and updating a string array using the useState hook in TypeScript:1. Begin by importing the useState hook from the

Currently, I am working on a React project that involves implementing a multi-select function for avatars. The goal is to allow users to select and deselect multiple avatars simultaneously. Here is what I have so far: export interface IStoreRecommendation ...

Setting the height of a popper or div to '100%' in a React application with Material-UI

I'm having some trouble with my JSX code. <Popper id={id} open={open} anchorEl={anchorEl} style={{opacity:'0.5',width:'100%',size:'100%'}}> <div style={{backgroundColor: 'red'}}>The content of th ...

Finding the correct index number for the active class - a step-by-step guide

I am currently troubleshooting an issue with my demo. I am having trouble retrieving the correct index number of .carousel-item.active. Even when the second slide is displayed, I continue to receive the index of the first slide. var totalItems = $(&apos ...

Creating a sleek horizontal drop-down navigation menu using Bootstrap 5 and CSS

Attempting to design a horizontal dropdown menu for small screens has been a challenge. However, all the resources I've come across seem to be outdated and ineffective. ...

Experiencing trouble with the integration of react native Vector icons in a current project

I'm encountering an issue with React Native Vector Icons. The error message I'm receiving says: Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You l ...

Troubleshooting a Vue 2 component's prop receiving an incorrect value

I'm currently working on creating a menu that navigates between categories. When a category has a sub-category, it should return a boolean value indicating whether it has a sub-category or not. <template> <select><slot></slot ...

How can CSS be used to create columns with text of different sizes?

Attempting to construct a text-based webpage entirely with HTML and CSS, the objective is to divide the page into two columns. The first column should occupy 2/3 of the width to accommodate the primary text, while the second column should take up the remai ...

Selecting the Static Modal backdrop will enlarge the Modal Content and introduce a scrollbar to the backdrop

I am encountering an issue with Bootstrap 4.4.1 where clicking outside of a static backdrop modal causes the size of the Modal content to scale up and adds a scrollbar to the backdrop. This problem persists in both Chrome and Firefox. How can I fix this? ...

What is the best way to obtain the final HTML output once all scripts have been executed

Is there a way to obtain the final HTML after all scripts have been executed? The scripts on the page are adding and changing controls and CSS, and I want to see the HTML of the display as a static page. Is there a method to achieve this? Edit: For exa ...

Ajax fails to send requests to PHP after changing the URL directory

After struggling to find a solution to my query, I have come to the realization that it has not been asked before. Despite enabling rewrite rules on my apache2 server in the .htaccess file located in the root directory, I am facing an issue with my ajax sc ...