DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
  1. DZone
  2. Coding
  3. Languages
  4. Creating Your Own HTML5 Colorwheel

Creating Your Own HTML5 Colorwheel

Andrey Prikaznov user avatar by
Andrey Prikaznov
·
Oct. 11, 12 · Interview
Like (2)
Save
Tweet
Share
42.75K Views

Join the DZone community and get the full member experience.

Join For Free

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 goal today is 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.

This would be a good time to test the demos and download the sources:

  • Live Demo 1
  • Live Demo 2
  • Live Demo 3
  • Live Demo 4
  • Live Demo 5
  • download in package

If you are ready – let’s start coding !

Step 1. HTML

Our first step is the 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
  • download in package

Conclusion

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

 

 

 

HTML

Published at DZone with permission of Andrey Prikaznov, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Load Balancing Pattern
  • 5 Factors When Selecting a Database
  • Kubernetes vs Docker: Differences Explained
  • OpenID Connect Flows

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: