Get hex value of clicked on color with jQuery

前端 未结 3 436
孤独总比滥情好
孤独总比滥情好 2021-01-07 00:37

I want to know how to make a color picker with jQuery that will allow you to click somewhere on the page and return the hex color value of the color that you clicked on.

3条回答
  •  误落风尘
    2021-01-07 01:19

    Bind a global click or mouseup event listener. Then, use canvas to obtain the pixel information. The pixel positions can be retrieved through the event object (event.pageX, event.pageY).

    See below for an example, which should work in future versions of FireFox. Currently, for security reasons, the drawWindow method is disabled for web pages. It should work in extensions, though. If you're truly interested, see the links for the similar methods in Chrome, Safari and Internet Explorer.

    var canvas = $(""); //Create the canvas element
    
    //Create a layer which overlaps the whole window
    canvas.css({position:"fixed", top:"0", left:"0",
                width:"100%", height:"100%", "z-index":9001});
    
    //Add an event listener to the canvas element
    canvas.click(function(ev){
        var x = ev.pageX, y = ev.pageY;
        var canvas = this.getContext("2d");
        canvas.drawWindow(window, x, y, 1, 1, "transparent");
        var data = canvas.getImageData(0, 0, 1, 1).data;
        var hex = rgb2hex(data[0], data[1], data[2]);
        alert(hex);
        $(this).remove();
    });
    
    canvas.appendTo("body:first"); //:first, in case of multiple  tags (hmm?)
    
    //Functions used for conversion from RGB to HEX
    function rgb2hex(R,G,B){return num2hex(R)+num2hex(G)+num2hex(B);}
    function num2hex(n){
        if (!n || !parseInt(n)) return "00";
        n = Math.max(0,Math.floor(Math.round(n),255)).toString(16);
        return n.length == 1 ? "0"+n : n;
    }
    

    References

    • Canvas examples - Learn more about canvas
    • drawWindow - FireFox method
    • visibleContentAsDataURL - Safari extensions
    • chrome.tabs.captureVisibleTab - Chrome extensions
    • HTA ActiveX control - Internet Explorer

提交回复
热议问题