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
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

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

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Related

  • How to Merge HTML Documents in Java
  • Exploring Intercooler.js: Simplify AJAX With HTML Attributes
  • Creating Scrolling Text With HTML, CSS, and JavaScript
  • Mastering SSR and CSR in Next.js: Building High-Performance Data Visualizations

Trending

  • Software Delivery at Scale: Centralized Jenkins Pipeline for Optimal Efficiency
  • Prioritizing Cloud Security Risks: A Developer's Guide to Tackling Security Debt
  • Rust, WASM, and Edge: Next-Level Performance
  • Infrastructure as Code (IaC) Beyond the Basics
  1. DZone
  2. Coding
  3. Languages
  4. Creating Your Own HTML5 Colorwheel

Creating Your Own HTML5 Colorwheel

By 
Andrey Prikaznov user avatar
Andrey Prikaznov
·
Oct. 11, 12 · Interview
Likes (2)
Comment
Save
Tweet
Share
45.0K 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.

Related

  • How to Merge HTML Documents in Java
  • Exploring Intercooler.js: Simplify AJAX With HTML Attributes
  • Creating Scrolling Text With HTML, CSS, and JavaScript
  • Mastering SSR and CSR in Next.js: Building High-Performance Data Visualizations

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

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

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!