How to create a color picker in html?

Rakesh Ram picture Rakesh Ram · Oct 26, 2016 · Viewed 22.3k times · Source

How to make a color picker, like we see in different websites where users can scroll down different colors and on click can get the color code?

I have tried of making a rows and columns but it was not so comfortable so want it to be like a color picker

You can take a look at the color box how i am trying it to be:

enter image description here

I have gone through different questions but I'm not able to solve this issue.

Answer

Gil Epshtain picture Gil Epshtain · Jun 27, 2018

Option #1 - Native HTML Color Picker

As mentioned in the previous answers you can use Native HTML color picker element:

<input type="color" />

Option #2 - 3rd party Color Picker

If the Native color picker not meet your criteria, since it has an obsolete look and not look as slick as modern Color-Pickers, you can use one of literally hundreds of color pickers on the web. Even a simple search on the NPM packages page will return a few hundreds results to pick from.
https://www.npmjs.com/search?q=color%20picker

Option #3 - Build your own Color-Picker

If you like me, and after a long search of color-picker library, you didn't find a picker that meet your criteria, you can build you color picker, which not take too long as I will demonstrate.

  1. Find a Color-Wheel image that will be your picker, for example:
    (a more complex colors-wheel probable needed in real application)
    enter image description here

  2. In your .html file, create a canvas element.

<canvas id="colorCanvas" class="color-canvas" width="250" height="250"></canvas>

  1. Give the canvas element border-radius: 50%, this will make the canvas round, so only clicks inside the circle will be fired, and clicks in the edge will be ignored (we will need click event in the next steps).

  2. In your JavaScript, init the canvas with your color-picker image, and listen to click events


function initColorPicker()
{
    var canvasEl = document.getElementById('colorCanvas');
    var canvasContext = canvasEl.getContext('2d');

    var image = new Image(250, 250);
    image.onload = () => canvasContext.drawImage(image, 0, 0, image.width, image.height); 
    image.src = "./images/myColorPickerImage.png";

    canvasEl.onclick = function(mouseEvent) 
    {
      var imgData = canvasContext.getImageData(mouseEvent.offsetX, mouseEvent.offsetY, 1, 1);
      var rgba = imgData.data;

      alert("rgba(" + rgba[0] + ", " + rgba[1] + ", " + rgba[2] + ", " + rgba[3] + ")");
    }
}