How to create your own Color Picker in Javascript?

I know that there are a lot of similar scripts on the net for different tastes and colors. But I wanted to write mine from scratch, and the first thing I did was google in search of a creation algorithm (color picker). As a result, I was disappointed because I did not find anything other than ready-made scripts, which is probably why after I figured out and wrote my color picker, I decided to share my experience in writing it.

Since I write in pure js without libraries (apart from the one that I write myself :)) in this post there will only be hardcore pure javascript.
What you need to know to write cp (abbreviated color picker):

1.CSS & html

I think the comments here do not need the simplest structure.
Now css
.right_arrow {
	border-bottom:6px solid transparent;
	border-left:10px solid transparent;
	border-top:6px solid transparent;
	border-right:10px solid black;
}//левая стрелка почти аналогично 
.circle {
	border:1px solid black;
	cursor: default;
	-moz-user-select: none;
	-khtml-user-select: none;
	user-select: none; 
	  -webkit-user-select: none;   

This, of course, is not all css code, but there is nothing more interesting (only positioning elements).


Well, now for the fun part, Javascript.
First you need to finish the structure (i.e. from drawing the Hue scale ), and I will do this on canvas (to reduce the number of images).

gradient: function(canva,w,h){
canva- объект canvas
h - высота шкалы
w- ширина
  var context, gradient, hue;
    context = canva.getContext("2d");
	gradient = context.createLinearGradient(w/2,h,w/2,0);
	 hue = [[255,0,0],[255,255,0],[0,255,0],[0,255,255],[0,0,255],[255,0,255],[255,0,0]];
         //цвета на шкале hue в rgb
	     for (var i=0; i <= 6;i++){
	         color = 'rgb('+hue[i][0]+','+hue[i][1]+','+hue[i][2]+')';
	             gradient.addColorStop(i*1/6, color);
			context.fillStyle = gradient;
			   context.fillRect(0,0, w ,h);	

You can see and touch what happened here . Next will go trivial event hooking (so I'll skip this code).
Now let's see which color model we will use, it will be HSV
HSV - color model in which the color coordinates are:

Hue - color tone, (for example, red, green or blue-blue). Varies within 0-360 °, however, sometimes it is reduced to the range 0-100 or 0-1.

Saturation - saturation. Varies between 0-100 or 0-1. The larger this parameter, the “cleaner” the color, so this parameter is sometimes called color purity. And the closer this parameter is to zero, the closer the color is to neutral gray.

Value (color value) or Brightness - brightness. It can also be set between 0-100 and 0-1.

how to implement this on our cp is clearly shown below (Fig. 1)

We have a Hue scale, we need to add a change in Saturation and Value (color value).
Since the value of S and V is 0-100, the question may arise:
what to do if the width and height of the block is more than 100?
var px_X = elem.clientWidth / 100;
в переменной px у нас значение пикселя. Пример:
ширина блока 180
180/100 , при смещение на 1 пиксель наше значение должно увеличиваться на 1,8;
var S = left / px_X;// в переменной left текущие смещение "круга" (div c id = "circle")относительно родителя
Math.round(S);//и не забываем округлять

When the “circle” is offset, we track the changes in S and V (for the visual effect of the color change, we change the background under the picture (the picture is semi transparent)).
But in order to change the background to need to be converted from HSV to RGB, I will not paint this stage much since there is a formula and if you compare it with the code below everything will be clear.
 hsv_rgb: function (H,S,V){
	 var f , p, q , t, lH;
     S /=100;
     V /=100;
      lH = Math.floor(H / 60);
      f = H/60 - lH;
      p = V * (1 - S); 
       q = V *(1 - S*f);
       t = V* (1 - (1-f)* S);
    switch (lH){
          case 0: R = V; G = t; B = p; break;
          case 1: R = q; G = V; B = p; break;
          case 2: R = p; G = V; B = t; break;
          case 3: R = p; G = q; B = V; break;
          case 4: R = t; G = p; B = V; break;
          case 5: R = V; G = p; B = q; break;
   return [parseInt(R*255), parseInt(G*255), parseInt(B*255)];

I wrote it myself because what I found on the network did not work correctly.
I hope that I gave the basic knowledge for creating cp in this post, so I’ll end here because I can increase the functionality for a long time and add conversion to different color formats ...

3. To summarize

That's what I got a demo .
In this post I tried to explain how to create cp without delving too much into the code because I didn’t see the point in Drag`n`Drop in it, there’s nothing complicated!
Thank you for your attention was CyBer_UA and this is my first post about javascript (I hope not the last).
The ps code in the final example is crooked (it was written a long time ago), it’s just that we just got around to writing this post.

Also popular now: