How to extract the colour of a pixel using Javascript and HTML 5

Meta Collective
Level Up Coding
Published in
3 min readNov 8, 2022

--

Photo by Umberto on Unsplash

In this post, I will go through how you can extract the colour code of a pixel in a given image.

Color picker in action on mouse move

We will use HTML 5’s Canvas element’s APIs and some vanilla javascript code.

The code for doing most of the heavy lifting is like this

As you can, we start by creating an empty canvas element and then draw that image like this. Note, how we are keeping the x & y coordinates on the canvas as 0,0 and we are also keeping the dimensions of the canvas the same as of the image.

canvas.width = img.width;
canvas.height = img.height;
let ctx: CanvasRenderingContext2D = canvas.getContext("2d") as CanvasRenderingContext2D;ctx.drawImage(img, 0, 0);

And then we make use of Canvas’s API and call the getImageData the function which will return an object representing the underlying pixel data for a specified portion of the canvas, which in our case is the entire canvas.

const imgData = ctx.getImageData(0, 0, canvas.width, canvas.height);

Now, we have a very large array of pixel data, so all we have to do now is to capture our mouse move event, and find that pixel data from the image data array

canvas.addEventListener("mousemove", (ev) => {
//as the mouse moves around the image
let cols = canvas.width;
let { offsetX, offsetY } = ev;

//call the method to get the r,g,b,a values for current pixel
let c = extractPixelColor(cols, offsetY, offsetX);

//build a colour string for
let colour = `rgb(${c.red}, ${c.green}, ${c.blue})`} ;
let hexCode = `#${[c.red, c.green, c.blue].map((x) =>
x.toString(16).padStart(2, "0")).join("")}`;

});

And lastly, to the fun part of getting the value of a pixel from the image data.

To do that, we have to understand, how pixels are arranged. For example, if we have an image of 5x5 pixels, then the array will look like the following image.

5x5 pixel image representation

Each element in the image above is representing a pixel and each pixel has 4 values in the order of RGBA (Red, Green, Blue & Alpha). Therefore, the array containing these pixels will have 5*5*4 = 100 elements. You can imagine this array getting really big once we load a bigger image.

Now, if you wish to extract the value of the element (2,2), then the Mathematical formula for that pixel index will be

PixelIndex = (Total number of columns * Row Number) + Column Number
// PixelIndex value for (2,2) will be (5*2)+3 = 28

Once you have the pixel index, getting the values for RGBA is pretty simple.

red = imgData[PixelIndex * 4]
green = imgData[(PixelIndex * 4) + 1]
blue = imgData[(PixelIndex * 4) + 2]
alpha = imgData[(PixelIndex * 4) + 3]

And lastly, the extractPixelColour function will look like this

After getting the RGB value in image data, you can convert them into hex value of the colour code like this

hexcolorcode = `#${[red, green, blue].map((x) => x.toString(16).padStart(2, "0")).join("")}`

Thanks for reading and if you want to support me, then please follow me and keep all of us on this platform by becoming a member.

Level Up Coding

Thanks for being a part of our community! Before you go:

🚀👉 Join the Level Up talent collective and find an amazing job

--

--

A collection of articles on technology, focusing on systems engineering, Cloud Computing, SDLC processes, & more. https://medium.com/@metacollective/membership