How to create a color picker in html?

后端 未结 5 702
醉话见心
醉话见心 2020-12-30 05:47

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 maki

5条回答
  •  天命终不由人
    2020-12-30 06:12

    Option #1 - Native HTML Color Picker

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

    
    

    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)

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

    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] + ")");
        }
    }
    
    

提交回复
热议问题