HTML5 Color Picker (canvas)

Tutorials

In our new tutorial we are going to create an easy, but effective color picker using HTML5. I think that you have already seen different jQuery versions of colorpicker, our today’s goal – to create something similar, and even better. In order to make it more unique, there are 5 different colorwheels which you can use. If you are ready – let’s start.

It is the very time to test our demos and download the sources:

Live Demo 1
Live Demo 2
Live Demo 3
Live Demo 4
Live Demo 5

[sociallocker]

download in package

[/sociallocker]


If you are ready – let’s start coding !


Step 1. HTML

Our first step is html markup:

01 <!-- preview element -->
02 <div class="preview"></div>
03 <!-- colorpicker element -->
04 <div class="colorpicker" style="display:none">
05     <canvas id="picker" var="1" width="300" height="300"></canvas>
06     <div class="controls">
07         <div><label>R</label> <input type="text" id="rVal" /></div>
08         <div><label>G</label> <input type="text" id="gVal" /></div>
09         <div><label>B</label> <input type="text" id="bVal" /></div>
10         <div><label>RGB</label> <input type="text" id="rgbVal" /></div>
11         <div><label>HEX</label> <input type="text" id="hexVal" /></div>
12     </div>
13 </div>

As you see, our color picker consists of two main components: the preview element and the hidden (by default) color picker element. Once we click by preview element – we will display color picker.

Step 2. JS

Our next step – is javascript. Please review our result code:

js/script.js

01 $(function(){
02     var bCanPreview = true// can preview
03     // create canvas and context objects
04     var canvas = document.getElementById('picker');
05     var ctx = canvas.getContext('2d');
06     // drawing active image
07     var image = new Image();
08     image.onload = function () {
09         ctx.drawImage(image, 0, 0, image.width, image.height); // draw the image on the canvas
10     }
11     // select desired colorwheel
12     var imageSrc = 'images/colorwheel1.png';
13     switch ($(canvas).attr('var')) {
14         case '2':
15             imageSrc = 'images/colorwheel2.png';
16             break;
17         case '3':
18             imageSrc = 'images/colorwheel3.png';
19             break;
20         case '4':
21             imageSrc = 'images/colorwheel4.png';
22             break;
23         case '5':
24             imageSrc = 'images/colorwheel5.png';
25             break;
26     }
27     image.src = imageSrc;
28     $('#picker').mousemove(function(e) { // mouse move handler
29         if (bCanPreview) {
30             // get coordinates of current position
31             var canvasOffset = $(canvas).offset();
32             var canvasX = Math.floor(e.pageX - canvasOffset.left);
33             var canvasY = Math.floor(e.pageY - canvasOffset.top);
34             // get current pixel
35             var imageData = ctx.getImageData(canvasX, canvasY, 1, 1);
36             var pixel = imageData.data;
37             // update preview color
38             var pixelColor = "rgb("+pixel[0]+", "+pixel[1]+", "+pixel[2]+")";
39             $('.preview').css('backgroundColor', pixelColor);
40             // update controls
41             $('#rVal').val(pixel[0]);
42             $('#gVal').val(pixel[1]);
43             $('#bVal').val(pixel[2]);
44             $('#rgbVal').val(pixel[0]+','+pixel[1]+','+pixel[2]);
45             var dColor = pixel[2] + 256 * pixel[1] + 65536 * pixel[0];
46             $('#hexVal').val('#' + ('0000' + dColor.toString(16)).substr(-6));
47         }
48     });
49     $('#picker').click(function(e) { // click event handler
50         bCanPreview = !bCanPreview;
51     });
52     $('.preview').click(function(e) { // preview click
53         $('.colorpicker').fadeToggle("slow""linear");
54         bCanPreview = true;
55     });
56 });

As you can see – there are only 64 lines of our colorpicker, so, as usual, in the beginning we create new canvas and context objects, then – draw an color wheel on the context. As you see – there is small switch case to select desired image (of colorwheel), I decided to use a new attribute for canvas object: ‘var’. So, you can easily change this colorwheel with different ‘var’ value, example:

1 <canvas id="picker" var="1" width="300" height="300"></canvas>
2 or
3 <canvas id="picker" var="2" width="300" height="300"></canvas>
4 or
5 <canvas id="picker" var="3" width="300" height="300"></canvas>
6 or
7 <canvas id="picker" var="4" width="300" height="300"></canvas>
8 or
9 <canvas id="picker" var="5" width="300" height="300"></canvas>

Well, finally, we have to add event handlers to next events: mousemove (by picker), click (by picker) and click (by preview). As you remember we have to display and hide color picker when we click at Preview element. In order to achieve it – I use ‘fadeToggle’ jQuery function (which was added in version 1.4.4):

1 $('.preview').click(function(e) { // preview click
2     $('.colorpicker').fadeToggle("slow""linear");
3     bCanPreview = true;
4 });

When we move our mouse over the Picker object – we should refresh information about current color, and, once we click at the Picker object – we should fix current color (or – disable preview by mousemove):

01 $('#picker').mousemove(function(e) { // mouse move handler
02     if (bCanPreview) {
03         // get coordinates of current position
04         var canvasOffset = $(canvas).offset();
05         var canvasX = Math.floor(e.pageX - canvasOffset.left);
06         var canvasY = Math.floor(e.pageY - canvasOffset.top);
07         // get current pixel
08         var imageData = ctx.getImageData(canvasX, canvasY, 1, 1);
09         var pixel = imageData.data;
10         // update preview color
11         var pixelColor = "rgb("+pixel[0]+", "+pixel[1]+", "+pixel[2]+")";
12         $('.preview').css('backgroundColor', pixelColor);
13         // update controls
14         $('#rVal').val(pixel[0]);
15         $('#gVal').val(pixel[1]);
16         $('#bVal').val(pixel[2]);
17         $('#rgbVal').val(pixel[0]+','+pixel[1]+','+pixel[2]);
18         var dColor = pixel[2] + 256 * pixel[1] + 65536 * pixel[0];
19         $('#hexVal').val('#' + ('0000' + dColor.toString(16)).substr(-6));
20     }
21 });
22 $('#picker').click(function(e) { // click event handler
23     bCanPreview = !bCanPreview;
24 });

Step 3. CSS

There are CSS styles of our color picker:

01 /* colorpicker styles */
02 .colorpicker {
03     background-color#222222;
04     border-radius: 5px 5px 5px 5px;
05     box-shadow: 2px 2px 2px #444444;
06     color#FFFFFF;
07     font-size12px;
08     positionabsolute;
09     width460px;
10 }
11 #picker {
12     cursorcrosshair;
13     floatleft;
14     margin10px;
15     border0;
16 }
17 .controls {
18     floatright;
19     margin10px;
20 }
21 .controls > div {
22     border1px solid #2F2F2F;
23     margin-bottom5px;
24     overflowhidden;
25     padding5px;
26 }
27 .controls label {
28     floatleft;
29 }
30 .controls > div input {
31     background-color#121212;
32     border1px solid #2F2F2F;
33     color#DDDDDD;
34     floatright;
35     font-size10px;
36     height14px;
37     margin-left6px;
38     text-aligncenter;
39     text-transformuppercase;
40     width75px;
41 }
42 .preview {
43     backgroundurl("../images/select.png"repeat scroll center center transparent;
44     border-radius: 3px;
45     box-shadow: 2px 2px 2px #444444;
46     cursorpointer;
47     height30px;
48     width30px;
49 }

Live Demo 1
Live Demo 2
Live Demo 3
Live Demo 4
Live Demo 5

Conclusion

We have just created own small and effective color picker with HTML5 (canvas). I hope that you like it. I will be glad to see your thanks and comments. Good luck!

Rate article