extract average colour from image in javascript

You can use the HTML5 Canvas API in JavaScript to extract the average color from an image. Here's a function that does this:

index.tsx
function getAverageColor(image) {
  // create a canvas element
  var canvas = document.createElement('canvas');
  canvas.width = image.width;
  canvas.height = image.height;

  // get the drawing context for the canvas
  var context = canvas.getContext('2d');

  // draw the image on the canvas
  context.drawImage(image, 0, 0);

  // get the image data from the canvas
  var imageData = context.getImageData(0, 0, image.width, image.height);
  var data = imageData.data;

  // loop through each pixel and calculate the average color
  var totalRed = 0;
  var totalGreen = 0;
  var totalBlue = 0;
  var totalPixels = 0;

  for (var i = 0; i < data.length; i += 4) {
    totalRed += data[i];
    totalGreen += data[i + 1];
    totalBlue += data[i + 2];
    totalPixels++;
  }

  var averageRed = Math.floor(totalRed / totalPixels);
  var averageGreen = Math.floor(totalGreen / totalPixels);
  var averageBlue = Math.floor(totalBlue / totalPixels);

  // return the average color as a string
  return 'rgb(' + averageRed + ',' + averageGreen + ',' + averageBlue + ')';
}
1069 chars
37 lines

You can call this function with an HTMLImageElement like this:

index.tsx
var image = new Image();
image.src = 'path/to/your/image.jpg';

image.onload = function() {
  var averageColor = getAverageColor(image);
  // do something with the average color
};
181 chars
8 lines

This function calculates the average color by adding up the red, green, and blue values for each pixel in the image, and then dividing by the total number of pixels. Finally, it returns the average color as an RGB string (e.g. "rgb(128, 64, 32)").

gistlibby LogSnag