DEV Community

achouri maher
achouri maher

Posted on

How to Extract Colors From an Image Using JavaScript and Canvas?

How to Extract Colors From an Image Using JavaScript and Canvas

Have you ever looked at an image and wanted to know the exact HEX color of a particular pixel?

Designers often need to extract colors from photographs, screenshots, logos, UI designs, and illustrations. You can do this directly in the browser without uploading the image to a server.

The browser Canvas API gives us everything we need.

Reading pixels with Canvas

The basic process is:

  1. Load an image.
  2. Draw it onto a canvas.
  3. Read the pixel data.
  4. Convert the RGBA values into a color format such as HEX or RGB.

The important API is getImageData().


javascript
const imageData = ctx.getImageData(x, y, 1, 1);
const pixel = imageData.data;

const r = pixel[0];
const g = pixel[1];
const b = pixel[2];
const a = pixel[3];
Enter fullscreen mode Exit fullscreen mode

Top comments (0)