HTML5 Color Picker (canvas)

HTML5 Color Picker (canvas)

9 2446
HTML5 Color Picker (canvas)

HTML5 Color Picker (canvas)

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

If you are ready – let’s start coding !


Step 1. HTML

Our first step is html markup:

<!-- preview element -->
<div class="preview"></div>

<!-- colorpicker element -->
<div class="colorpicker" style="display:none">
    <canvas id="picker" var="1" width="300" height="300"></canvas>

    <div class="controls">
        <div><label>R</label> <input type="text" id="rVal" /></div>
        <div><label>G</label> <input type="text" id="gVal" /></div>
        <div><label>B</label> <input type="text" id="bVal" /></div>
        <div><label>RGB</label> <input type="text" id="rgbVal" /></div>
        <div><label>HEX</label> <input type="text" id="hexVal" /></div>
    </div>
</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

$(function(){
    var bCanPreview = true; // can preview

    // create canvas and context objects
    var canvas = document.getElementById('picker');
    var ctx = canvas.getContext('2d');

    // drawing active image
    var image = new Image();
    image.onload = function () {
        ctx.drawImage(image, 0, 0, image.width, image.height); // draw the image on the canvas
    }

    // select desired colorwheel
    var imageSrc = 'images/colorwheel1.png';
    switch ($(canvas).attr('var')) {
        case '2':
            imageSrc = 'images/colorwheel2.png';
            break;
        case '3':
            imageSrc = 'images/colorwheel3.png';
            break;
        case '4':
            imageSrc = 'images/colorwheel4.png';
            break;
        case '5':
            imageSrc = 'images/colorwheel5.png';
            break;
    }
    image.src = imageSrc;

    $('#picker').mousemove(function(e) { // mouse move handler
        if (bCanPreview) {
            // get coordinates of current position
            var canvasOffset = $(canvas).offset();
            var canvasX = Math.floor(e.pageX - canvasOffset.left);
            var canvasY = Math.floor(e.pageY - canvasOffset.top);

            // get current pixel
            var imageData = ctx.getImageData(canvasX, canvasY, 1, 1);
            var pixel = imageData.data;

            // update preview color
            var pixelColor = "rgb("+pixel[0]+", "+pixel[1]+", "+pixel[2]+")";
            $('.preview').css('backgroundColor', pixelColor);

            // update controls
            $('#rVal').val(pixel[0]);
            $('#gVal').val(pixel[1]);
            $('#bVal').val(pixel[2]);
            $('#rgbVal').val(pixel[0]+','+pixel[1]+','+pixel[2]);

            var dColor = pixel[2] + 256 * pixel[1] + 65536 * pixel[0];
            $('#hexVal').val('#' + ('0000' + dColor.toString(16)).substr(-6));
        }
    });
    $('#picker').click(function(e) { // click event handler
        bCanPreview = !bCanPreview;
    }); 
    $('.preview').click(function(e) { // preview click
        $('.colorpicker').fadeToggle("slow", "linear");
        bCanPreview = true;
    });
});

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:

<canvas id="picker" var="1" width="300" height="300"></canvas>
or
<canvas id="picker" var="2" width="300" height="300"></canvas>
or
<canvas id="picker" var="3" width="300" height="300"></canvas>
or
<canvas id="picker" var="4" width="300" height="300"></canvas>
or
<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):

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

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):

$('#picker').mousemove(function(e) { // mouse move handler
    if (bCanPreview) {
        // get coordinates of current position
        var canvasOffset = $(canvas).offset();
        var canvasX = Math.floor(e.pageX - canvasOffset.left);
        var canvasY = Math.floor(e.pageY - canvasOffset.top);

        // get current pixel
        var imageData = ctx.getImageData(canvasX, canvasY, 1, 1);
        var pixel = imageData.data;

        // update preview color
        var pixelColor = "rgb("+pixel[0]+", "+pixel[1]+", "+pixel[2]+")";
        $('.preview').css('backgroundColor', pixelColor);

        // update controls
        $('#rVal').val(pixel[0]);
        $('#gVal').val(pixel[1]);
        $('#bVal').val(pixel[2]);
        $('#rgbVal').val(pixel[0]+','+pixel[1]+','+pixel[2]);

        var dColor = pixel[2] + 256 * pixel[1] + 65536 * pixel[0];
        $('#hexVal').val('#' + ('0000' + dColor.toString(16)).substr(-6));
    }
});
$('#picker').click(function(e) { // click event handler
    bCanPreview = !bCanPreview;
}); 

Step 3. CSS

There are CSS styles of our color picker:

/* colorpicker styles */
.colorpicker {
    background-color: #222222;
    border-radius: 5px 5px 5px 5px;
    box-shadow: 2px 2px 2px #444444;
    color: #FFFFFF;
    font-size: 12px;
    position: absolute;
    width: 460px;
}
#picker {
    cursor: crosshair;
    float: left;
    margin: 10px;
    border: 0;
}
.controls {
    float: right;
    margin: 10px;
}
.controls > div {
    border: 1px solid #2F2F2F;
    margin-bottom: 5px;
    overflow: hidden;
    padding: 5px;
}
.controls label {
    float: left;
}
.controls > div input {
    background-color: #121212;
    border: 1px solid #2F2F2F;
    color: #DDDDDD;
    float: right;
    font-size: 10px;
    height: 14px;
    margin-left: 6px;
    text-align: center;
    text-transform: uppercase;
    width: 75px;
}
.preview {
    background: url("../images/select.png") repeat scroll center center transparent;
    border-radius: 3px;
    box-shadow: 2px 2px 2px #444444;
    cursor: pointer;
    height: 30px;
    width: 30px;
}

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!

SIMILAR ARTICLES


9 COMMENTS

  1. Hi Andrew ,
    Thanks, a good lesson.
    It would be interesting, if you choose color changed and the color of the text.

    • Hello Jeff,
      You can’t select ‘transparent’ color using color circle. But, you can prepare a new button (for toolbar) to select ‘transparent’ color

  2. this is a great tutorial but it looks like the black hex color is missing a 0

    i did my own and thought it was something i had done – but come back and its definitely missing’

    try demo1 and click on the outer black area and you will see what i am talking about…

    screenshot here: http://screencast.com/t/DT9ggJZR

    any help greatly appreciated

    • Hello Jay,
      Yes, you are right, to fix this problem please goto lone 65 of our JS script, and change ’0000′ to ’00000′

  3. I downloaded the package and ran it on my system……I could not choose color from the image…any reasons why??? Thanks in advance.

Leave a Reply