DEV Community

Bhaskar Rana
Bhaskar Rana

Posted on

Create an HTML Color picker using JavaScript

Have you ever wondered how developers make online HTML/CSS color picker? Don't worry, I will walk you through the basic guide which can help you a lot if you were looking for some nice tutorial on how to create the one.
Ok, so without wasting time, let's get started.

Any HTML/CSS color picker has two main parts, first a color canvas and second a color slider.
The main color like red, green, blue, etc. is chosen on the color slider and the color canvas helps us finding some more variations of the chosen color.
Refer to the images below:

Alt Text

In the above image the left one is the color canvas and the right one is the color slider.

Let's start creating the color canvas first.
The color canvas is basically a mixture of black, white and the selected color's gradients.
Means color canvas = vertical gradient of white to black + horizontal gradient of the selected color
Refer to the image below:
Alt Text
I hope now you got the idea.
That's cool but how to create it???? That what we will do next.

Step1: Create a canvas of any dimensions you want. Here, I will use 300px width and 300px height. To do that we will use html <canvas> element.
So just add
<canvas width="300px" height="300px" id="color_canvas"></canvas> in your html file.

Now add the below code in your JavaScript file:

var colorCanvas = document.getElementById('color_canvas');
var ColorCtx = colorCanvas .getContext('2d');  // This create a 2D context for the canvas

// Create a Vertical Gradient(white to black)
 let gradientV = ColorCtx .createLinearGradient(0, 0, 0, 300);
 gradientV.addColorStop(0, 'rgba(0,0,0,0)');
 gradientV.addColorStop(1, '#000');
 ColorCtx .fillStyle = gradientV;
 ColorCtx .fillRect(0, 0, ColorCtx .canvas.width, 
 ColorCtx .canvas.height); 
Enter fullscreen mode Exit fullscreen mode

This will result in creating a 2 dimensional 300X300 canvas with a white to black color gradient. See the image below:
image
Now, in the similar way we have to create a horizontal gradient of any color that we want(for now we are using blue color, later it will change dynamically).
To do that add the below code in the beginning of your JavaScript file:

// Create a horizontal gradient
var color = '#0000ff'
let gradientH = ColorCtx .createLinearGradient(0, 0, ColorCtx .canvas.width, 0);
gradientH.addColorStop(0, '#fff');
gradientH.addColorStop(1, color);
ColorCtx .fillStyle = gradientH;
ColorCtx .fillRect(0, 0, ColorCtx .canvas.width, ColorCtx .canvas.height);
Enter fullscreen mode Exit fullscreen mode

Now your JavaScript file will look something like this:

var colorCanvas = document.getElementById('color_canvas');
var ColorCtx = colorCanvas .getContext('2d');  // This create a 2D context for the canvas

var color = 'rgba(0,0,255,1)';
let gradientH = ColorCtx .createLinearGradient(0, 0, ColorCtx .canvas.width, 0);
gradientH.addColorStop(0, '#fff');
gradientH.addColorStop(1, color);
ColorCtx .fillStyle = gradientH;
ColorCtx .fillRect(0, 0, ColorCtx .canvas.width, ColorCtx .canvas.height);


// Create a Vertical Gradient(white to black)
 let gradientV = ColorCtx .createLinearGradient(0, 0, 0, 300);
 gradientV.addColorStop(0, 'rgba(0,0,0,0)');
 gradientV.addColorStop(1, '#000');
 ColorCtx .fillStyle = gradientV;
 ColorCtx .fillRect(0, 0, ColorCtx .canvas.width, 
 ColorCtx .canvas.height); 
Enter fullscreen mode Exit fullscreen mode

Now if you refresh your html page it will create an actual canvas for you. Refer to the image below:
image
Awesome!!!
Now, we are done with our first step. Let's move forward to create the next part.

Step 2: In this step, we will try to find out the color of the pixel where we have clicked the mouse on our color canvas.

To achieve this, the very first thing we need is the X,Y coordinates of the point where we have clicked the mouse.
Which in JavaScript can be achieved by the the event listener functions.
Add the below JavaScript code in your script file:

colorCanvas.addEventListener('click',function(event){
    let x = event.clientX;  // Get X coordinate
    let y = event.clientY;  // Get Y coordinate
    pixel = ColorCtx.getImageData(x,y,1,1)['data'];   // Read pixel Color
    rgb = `rgb(${pixel[0]},${pixel[1]},${pixel[2]})`;
    document.body.style.background = rgb;    // Set this color to body of the document
 });
Enter fullscreen mode Exit fullscreen mode

Boom!!!!
Now if you click anywhere on the color canvas, it will set that color to the body of the document.
This is awesome!!!
Below is the image how it looks and I think we are very close to make our own color picker.
image

As this post has already become very long. Therefore I am stopping the coding part here. Don't panic I will walk you through the next steps also, which are very similar to what we have done so far.

Step 3: In this step we will make the marker which will move along with the mouse cursor on the color canvas to choose our desired color from it.
To do that need a little CSS along with JavaScript.
The first thing we need is the X,Y coordinates of the mouse cursor. That part we have already discussed.
Next thing is setting the position of the marker at current mouse position.
To do that we have to make use of CSS Position Property which will help us changing position of the cursor dynamically.

  1. Set the position property of the canvas to relative.
  2. Set the position property of the marker to absolute.

After doing this, make use of CSS top property and CSS left property to set the position of the marker dynamically.
i.e.

marker.style.top = y;
marker.style.left = x;
Enter fullscreen mode Exit fullscreen mode

Add the below code in the event listener we have already created and it will change the position of the marker dynamically along with the mouse cursor.

Awesome!!!!
Now we are almost done.

You can follow the same steps to create the color slider also. The only difference is that it will have 7 colors gradient. Which depends on your requirement, you can have more or less number of colors.
The dimensions of the color slider which I prefer is 40 X 300px. You are free to choose any.

I have took the references from these two color pickers:

  1. HTML Color Picker
  2. HTML Color Picker

That's all for this tutorial. If you have any doubts or need any help you can comment below. I will try my 100% to clear your doubts.

Discussion (0)