Categories
JavaScript Answers

How to get average color of image via JavaScript?

Spread the love

Sometimes, we want to get average color of image via JavaScript.

In this article, we’ll look at how to get average color of image via JavaScript.

How to get average color of image via JavaScript?

To get average color of image via JavaScript, we can put the image in a canvas and then use the canvas context getImageData method.

For instance, we write

const getAverageRgb = (img) => {
  const context = document.createElement("canvas").getContext("2d");
  if (typeof img === "string") {
    const img = new Image();
    img.setAttribute("crossOrigin", "");
    img.src = src;
    img.onload = () => {
      context.imageSmoothingEnabled = true;
      context.drawImage(img, 0, 0, 1, 1);
      console.log(context.getImageData(1, 1, 1, 1).data.slice(0, 3));
    };
  }
};

to define the getAverageRgb function.

In it, we create a canvas element with createElement and get its context with getContext.

Then we create the img image and set its onload property to a function that gets the average rgb value with getImageData.

Conclusion

To get average color of image via JavaScript, we can put the image in a canvas and then use the canvas context getImageData method.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *