Giter Club home page Giter Club logo

flexicolorpicker's Introduction

Demo & discussion

Visit: http://www.daviddurman.com/flexi-color-picker

Features

  • no Flash, images or 1px divs
  • no dependency on an external JavaScript library
  • dimensions of both the picker and the slider areas can be adjusted arbitrarily
  • minimalistic (about 400 loc including comments)
  • support for a large scale of browsers (including mobile browsers)
  • understandable (no magic behind, code can be easily read and therefore adjusted)
  • styleable in CSS
  • position of the slider and the picker areas is not hardcoded and can be changed in CSS
  • HSV, RGB and HEX output/input
  • indicators (pointers to the slider and picker areas) can be arbitrary HTML elements (images, divs, spans, ...) styleable in CSS
  • ready-to-use themes (stored in one CSS stylesheet)

Description

FlexiColorPicker is based on HSV color model. The only two parts of the color picker are therefore the slider for selecting hue value and the picker for selecting saturation and value. Both the slider and picker are HTML elements (usually <div>'s) that serve as wrappers for SVG/VML gradient rectangles. The slider gradient rectangle represents the hue value (gradient with 9 stop-colors). The two overlapping black and white gradient rectangles of the picker represent the saturation and value values. The top level elements (<svg> in case of SVG enabled browser and <div> in case of VML enabled browser) that wrap each of the slider and picker gradient rectangles have set width and height to 100% which means that the color picker components (slider and picker) adjust themselfs automatically to the dimensions of the slider and picker HTML elements.

API

ColorPicker(colorPickerElement, function(hex, hsv, rgb) { /*do something when the color changes */ })

This is the no-hassle form of creating the color picker. This is the recommended call.

Example:

    <div id="mycolorpicker" class="cp-default"></div>
    <script>
        ColorPicker(document.getElementById('mycolorpicker'), function(hex, hsv, rgb) {
            document.body.style.backgroundColor = hex;
        });
    </script>

ColorPicker.prototype.setHsv(hsv)

Sets HSV value.

Example:

    var cp = ColorPicker(document.getElementById('mycolorpicker'), function() {});
    cp.setHsv({ h: 180, s: .2, v: .7 });

ColorPicker.prototype.setRgb(rgb)

Sets RGB value.

Example:

    var cp = ColorPicker(document.getElementById('mycolorpicker'), function() {});
    cp.setRgb({ r: 120, g: 205, b: 18 });

ColorPicker.prototype.setHex(hex)

Sets HEX value.

Example:

    var cp = ColorPicker(document.getElementById('mycolorpicker'), function() {});
    cp.setHex('#AB12FE');

ColorPicker.positionIndicators(sliderIndicator, pickerIndicator, sliderCoordinate, pickerCoordinate)

Positions indicators in the slider and the picker. This is a helper function that is supposed to be called in the callback function passed as the fourth argument to the ColorPicker function. The only thing it does is setting the top and left CSS coordinate on the sliderIndicator and pickerIndicator HTML elements. If you use the no-hassle form (see above), you don't have to deal with this function at all.

Example:

            ColorPicker(
                    document.getElementById('slider'), 
                    document.getElementById('picker'), 

                    function(hex, hsv, rgb, pickerCoordinate, sliderCoordinate) {
    
                        ColorPicker.positionIndicators(
                            document.getElementById('slider-indicator'),
                            document.getElementById('picker-indicator'),
                            sliderCoordinate, pickerCoordinate
                        );
    
                        document.body.style.backgroundColor = hex;
                });

ColorPicker.fixIndicators(sliderIndicator, pickerIndicator)

This helper function just sets the pointer-events CSS property to 'none' on both the sliderIndicator and pickerIndicator. This is necessary otherwise any mouse event (click, mousedown, mousemove) triggered on the sliderIndicator or pickerIndicator HTML elements would be cought instead of bypassed to the slider and the picker area, hence preventing the color picker to catch these UI events in order to change color. As pointer-events CSS property is not supported in all browsers, this function might workaround this issue in the future. At this time, setting pointer-events: none in CSS on the slider and picker indicators is equivalent.

Again, if you use the no-hassle form (see above), you don't have to deal with this function at all.

Examples

The basic example demonstrates the minimalism of the FlexiColorPicker. More useful examples follow.

Basic

        <html>
          <head>
            <script type="text/javascript" src="colorpicker.js"></script>
            <style type="text/css">
              #picker { width: 200px; height: 200px }
              #slider { width: 30px; height: 200px }
            </style>
          </head>
          <body>

            <div id="picker"></div>
            <div id="slider"></div>

            <script type="text/javascript">

              ColorPicker(

                document.getElementById('slider'),
                document.getElementById('picker'),

                function(hex, hsv, rgb) {
                  console.log(hsv.h, hsv.s, hsv.v);         // [0-359], [0-1], [0-1]
                  console.log(rgb.r, rgb.g, rgb.b);         // [0-255], [0-255], [0-255]
                  document.body.style.backgroundColor = hex;        // #HEX
                });

            </script>
          </body>
        </html>

Note that you can set arbitrary dimensions, position, border and other CSS properties on the slider and picker elements as you would do with any other HTML element on the page.

Advanced

This is an advanced example showing how to work with custom indicators.

    <html>
      <head>
        <script type="text/javascript" src="../colorpicker.js"></script>
        <style type="text/css">
    
            #picker-wrapper {
                width: 200px;
                height: 200px;
                position: relative;
            }
            #slider-wrapper {
                width: 30px;
                height: 200px;
                position: relative;
            }
            #picker-indicator {
                width: 3px;
                height: 3px;
                position: absolute;
                border: 1px solid white;
            }
            #slider-indicator {
                width: 100%;
                height: 10px;
                position: absolute;
                border: 1px solid black;
            }
        </style>
      </head>
      <body>
    
          <div id="picker-wrapper">
              <div id="picker"></div>
              <div id="picker-indicator"></div>
          </div>
          <div id="slider-wrapper">
              <div id="slider"></div>
              <div id="slider-indicator"></div>
          </div>
    
          <script type="text/javascript">
    
            ColorPicker.fixIndicators(
                    document.getElementById('slider-indicator'),
                    document.getElementById('picker-indicator'));
    
            ColorPicker(
                    document.getElementById('slider'), 
                    document.getElementById('picker'), 

                    function(hex, hsv, rgb, pickerCoordinate, sliderCoordinate) {
    
                        ColorPicker.positionIndicators(
                            document.getElementById('slider-indicator'),
                            document.getElementById('picker-indicator'),
                            sliderCoordinate, pickerCoordinate
                        );
    
                        document.body.style.backgroundColor = hex;
                });
    
          </script>
      </body>
    </html>

Note how the indicators work. There is no built-in indicators in FlexiColorPicker, instead, the user has a freedom to set their own indicators as normal HTML elements styled in CSS (or use one of the ready-to-use themes packaged with FlexiColorPicker).

No hassle

If you don't want to deal with any of the above mentioned details and you're just looking for a copy-paste (one function call-like) color picker, see this example.

    <html>
      <head>
        <script type="text/javascript" src="../colorpicker.js"></script>
        <link rel="stylesheet" type="text/css" href="../themes.css" />
      </head>
      <body>
    
        <div id="color-picker" class="cp-default"></div>
    
        <script type="text/javascript">
    
          ColorPicker(
    
            document.getElementById('color-picker'),
    
            function(hex, hsv, rgb) {
                console.log(hsv.h, hsv.s, hsv.v);         // [0-359], [0-1], [0-1]
                console.log(rgb.r, rgb.g, rgb.b);         // [0-255], [0-255], [0-255]
                document.body.style.backgroundColor = hex;        // #HEX
            });
    
        </script>
      </body>
    </html>

The ColorPicker function has recognized only two arguments which means that it builds the HTML needed for you and also fixes and positions indicators automatically.

License

FlexiColorPicker is licensed under the MIT license:

Copyright (c) 2011 - 2012 David Durman

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Bitdeli Badge

flexicolorpicker's People

Contributors

bitdeli-chef avatar daviddurman avatar edelooff avatar kaore avatar mathieuflamant avatar rappid-deploy avatar ryandao avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

flexicolorpicker's Issues

Need support for destroy method

I want to use this color picker in angular but I'll need a way to properly destroy it. The initialization of the color picker adds event listeners that must be removed when the color picker is removed from the DOM.

picker-indicator resizes when Colorpicker is appended somewhere else

Hi,
First off, kudos to making the simplest & sleakest color picker available out there.
In order to avoid creating color pickers for every color setting on a page, I wanted to use 1 color picker & move it to every setting once clicked. However, the picker-indicator is disproportionately resized when this is done (I don't really get why it is resized at all).
This is what it looks like after being moved:

My temporary solution is to set .picker-indicator { width: 1px !important }.. What causes this?

Allow more that one picker per document

Only the first picker of the document is working, probably because of the "id" used for the gradient.
You could handle this by adding a counter in the ColorPicker object, and changing the id and the fill value after the cloneNode.

Null is not an object exception - safari browser

Hello,

I am getting TypeError: null is not an object (evaluating 'hsvGradient.id = 'gradient-hsv-' + uniqID') in my safari browser with latest Mac OS version.
Attached are the OS and Safari version snapshots.

Thanks.

screen shot 2015-10-14 at 11 59 40 am

screen shot 2015-10-14 at 11 59 54 am

Afzettten Scrummaster

Ik stel voor op muiterij te plegen.

Onze scrum master doet zijn werk ondermaats en staat niet open voor kritiek.
Hij houdt andere mensen van hun werk af door samen youtube videos te kijken en hij gaat compleet tegen het agile principe in:
hij is bezig met een eigen color picker te maken terwijl er 1001 javascript libraries op internet staan die aan alle eisen voldoen en een flexibele license hebben.
Dit gaat in tegen het principe: maximize work not done.

Not working on safari.

downloaded it, extract it, and preview demo on browsers. Chrome working fine, but safari messed up. what did i miss.

screen shot 2017-01-03 at 3 06 26 pm

Bug in rgb2hsv for end of hue spectrum

rgb2hsv(255, 0, 220) 0.8627450980392157 for Hue, causing Flexi picker to get lost in the hue picket.

The real hue should be 5.137254901960784.

Here is what's missing:

@@ -148,7 +148,7 @@
         V = Math.max(r, g, b);
         C = V - Math.min(r, g, b);
         H = (C == 0 ? null :
-             V == r ? (g - b) / C :
+             V == r ? (g - b) / C + (g < b ? 6 : 0):
              V == g ? (b - r) / C + 2 :
                       (r - g) / C + 4);
         H = (H % 6) * 60;

problem with minified version

changing the slider position resets the picker position to upper right corner.
the non minifed version works fine
minifying with uglify works .
uglify also produces a slightly smaller sized file .

Saturation and value not reset when click on slide

In slideListener, when a click is received on the slider, the saturation and value are resetted in RGB and Hex values, but not in HSV object. Fix:

+            ctx.s = 1, ctx.v = 1;
             var c = hsv2rgb(ctx.h, 1, 1);
             pickerElement.style.backgroundColor = c.hex;

Sliding the hue slider should not reset brightness and saturation

Pretty much every other picker allows editing of three HSB components separately, without reseting any information. Flexi behaviour, that resets saturation and brightness, made me switch to another color picker. However, I do like Flexi the most of all color pickers I tried, and I consider the non-reseting behaviour correct, so I'm submitting this as an issue.

Strange case where both color boxes are black

Hi David,
Sorry if it's not the correct place to post, probably not a bug of your code but wondering if you ever met this issue. Suddenly, my picker looks like that, sometimes with a random color but most often black. The resulting color picked is actually correct.

capture d ecran 2014-11-25 a 15 17 31

Thanks for your insight, you can close if you have no idea ;-)
Charles

Incorrect hue gradient used

I don't know how you get that values... for me it looks like you randomly picked them from some sample...
That are correct:
#ff0000 0%,
#ffff00 16.7%,
#00ff00 33.3%,
#00ffff 50%,
#0000ff 66.7%,
#ff00ff 83.3%,
#ff0000 100%

here is some math logic used, dude
hue wiki

ps i like your rgb2hex method though)) its awesome!
Best regards)

How to change size dynamically?

I have tried to implement the basic sample and it works fine to start with but how do I change the size afterwards?

The case is that I want to use the color picker on mobile device where I have to scale the height and width according to the 'current' resolution so I can't use static sizes like in the css classes. If I change the size of the picker, then it behaves odd afterwards until I have picked another color in the picker.

How do I get around this problem?

Allow dragging on picker and slider

It should be quite easy and user-friendly to allow dragging on the picker and the slider, listening to "mousedown" and "mousemove" instead of click.

hsv2rgb is broken

Implementation of hsv2rgb function is incorrect.

If you convert color: #81c111 from hex to hsv and then back to hex you will get: #80c110

Problem is with decimal rounding.
Here is my fixed version:

    function hsv2rgb(hsv) {
        var R, G, B, X, C;
        var h = (hsv.h % 360) / 60;

        C = hsv.v * hsv.s;
        X = C * (1 - Math.abs(h % 2 - 1));
        R = G = B = hsv.v - C;

        h = ~~h;
        R += [C, X, 0, 0, X, C][h];
        G += [X, C, C, X, 0, 0][h];
        B += [0, 0, X, C, C, X][h];

        var r = Math.round(R * 255);
        var g = Math.round(G * 255);
        var b = Math.round(B * 255);
        return { r: r, g: g, b: b, hex: "#" + (16777216 | b | (g << 8) | (r << 16)).toString(16).slice(1), a:hsv.a };
    }

Not working in IE browser

Hi,

First of all thankyou for the great plugin. I have an issue in IE, please find the error details below, please let me know on how to proceed.

Webpage error details

User Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E)

Timestamp: Thu, 1 Aug 2013 13:35:37 UTC

Message: Object doesn't support this property or method

Line: 242

Char: 13

Code: 0

URI: http://xyz.com/assets/js/library/colorpicker.js

line 242 has the following code: this.slideElement = element.getElementsByClassName('slide')[0];

Message: Object doesn't support this property or method

Line: 140

Char: 2

Code: 0

URI: http://xyz.com/assets/js/checkout.js

line no 140 has the following code: var cpDefault = ColorPicker(document.getElementById('default'), updateInputs);

Note: i am using the code that was present in the showcase.js file, modified it according to my requirements.
Also the showcase example is not working in IE. Currently i am checking in IE 8

Two FlexiColorPicker in the same page doesn't work - Firefox Only

I try to put two color picker in the same page, im using wijmo for dialogs and i show a dialog with the color picker inside but the first color picker works fine and the second doesnt work. This issue is only in for firefox because the same page i tested in IE9, IE10, IE11 and works fine. I dont know what to do. If somebody can help me i will appreciate.

Regard.

Peter.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.