Navigation

How to create a color picker with HTML5 Canvas

By Sara Vieira | How To, HTML, JavaScript | Mar 21, 2013

Creating canvas apps is the new thing, we can even create games with it, it’s supported in all major browsers both desktop and mobile, and that makes it a more viable solution than using Flash.

In this tutorial we are going to use the canvas element to create a simple color picker that doesn’t require any Flash, all you’ll need is a text editor and a browser.

Before we start, take a look at what we’ll build here. You can also download the source files here. Note that if you’re going to test the demo locally, you’ll need to use a browser other than Chrome; Chrome’s security model means that the script will only work online.

 

The HTML

For this example the HTML will be very minimal, all we need in order for the color picker to work is a canvas element and some place to show our selected color in RGB and in HEX formats, so all we need is this:

<canvas width="600" height="440" id="canvas_picker"></canvas>
<div id="hex">HEX: <input type="text"></input></div>
<div id="rgb">RGB: <input type="text"></input></div>

Since we will use a background image with the color pallete I made my canvas the width and height of that image and the values for the selecetd color will appear in the inputs for easier selection.

You should also add jQuery to your page since we will be using some jQuery code.

 

The JavaScript

The first thing we need to do in order to make the color picker work is to get the canvas and its context and to do that all we need is a line of code, like so:

var canvas = document.getElementById('canvas_picker').getContext('2d');

Now that we have got the canvas element and its context, we can start by setting the image as the background of the canvas. To do this we need to create an image object and make its source the URL of the image. When this image has loaded we need to draw it into the canvas:

var img = new Image();
img.src = 'image.jpg';
$(img).load(function(){
  canvas.drawImage(img,0,0);
});

So far so good, right ?

Well, this is the part where we need to define what happens when you click somewhere in the canvas, and if you think about it, you first need to get the user’s cursor position in the canvas to see where they clicked, like so:

$('#canvas_picker').click(function(event){
var x = event.pageX - this.offsetLeft;
var y = event.pageY - this.offsetTop;

With these two lines of code we can see where the user clicked and what we are doing is getting the cordinates of where the user clicked and then subtracting from that the offset of the canvas. That will tell us where the user clicked relative to the position of the canvas.

Our next step is to get the RGB values of the place the user clicked and to do that we need we to use the function getImageData and attach the x and y position of the click:

var imgData = canvas.getImageData(x, y, 1, 1).data;
var R = imgData[0];
var G = imgData[1];
var B = imgData[2];

We now have these values stored inside R , G and B variables but we want to display this information to the user in a way they can easily can read it so we need to create an RGB variable that holds these three values separeted by commas and then present this as the value of one of our input fields:

var rgb = R + ',' + G + ',' + B;
  $('#rgb input').val(rgb);
});

And if you test it out now you already have a fully functional color picker that retrieves the RGB value of anywhere you click, but to make this a little bit better we can add a function from Javascripter that converts RGB values to HEX values; the function is:

function rgbToHex(R,G,B) {return toHex(R)+toHex(G)+toHex(B)}
function toHex(n) {
  n = parseInt(n,10);
  if (isNaN(n)) return "00";
  n = Math.max(0,Math.min(n,255));return "0123456789ABCDEF".charAt((n-n%16)/16) + "0123456789ABCDEF".charAt(n%16);
}

Now that we got this function all we need to do in order to present the HEX values is perform the function with our RBG values and then set the value of the input to be HEX color with a # before and with the function already in place this is quite simple :

// after declaring the RGB variable   
var hex = rgbToHex(R,G,B);
// after setting the RGB value
$('#hex input').val('#' + hex);

 

The Full Code

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Colorpicker demo</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
</head>
<body>

<canvas width="600" height="440" id="canvas_picker"></canvas>
<div id="hex">HEX: <input type="text"></input></div>
<div id="rgb">RGB: <input type="text"></input></div>

<script type="text/javascript">
var canvas = document.getElementById('canvas_picker').getContext('2d');

// create an image object and get it’s source
var img = new Image();
img.src = 'image.jpg';

// copy the image to the canvas
$(img).load(function(){
canvas.drawImage(img,0,0);
});

// http://www.javascripter.net/faq/rgbtohex.htm
function rgbToHex(R,G,B) {return toHex(R)+toHex(G)+toHex(B)}
function toHex(n) {
n = parseInt(n,10);
if (isNaN(n)) return "00";
n = Math.max(0,Math.min(n,255));
return "0123456789ABCDEF".charAt((n-n%16)/16) + "0123456789ABCDEF".charAt(n%16);
}
$('#canvas_picker').click(function(event){
// getting user coordinates
var x = event.pageX - this.offsetLeft;
var y = event.pageY - this.offsetTop;
// getting image data and RGB values
var img_data = canvas.getImageData(x, y, 1, 1).data;
var R = img_data[0];
var G = img_data[1];
var B = img_data[2]; var rgb = R + ',' + G + ',' + B;
// convert RGB to HEX
var hex = rgbToHex(R,G,B);
// making the color the value of the input
$('#rgb input').val(rgb);
$('#hex input').val('#' + hex);
});
</script>

</body>
</html>

 

Conclusion

I hope that with this tutorial you have realized the potential there is in creating apps with canvas. There are a lot more advanced apps out there, people are even making games with canvas so it’s a thing to explore because you can build some amazing things with it.

 

What other uses have you found for Canvas? What would you like to be able to use it for? Let us know in the comments.

Featured image/thumbnail, color picker image via Shutterstock.

Share this post
Comments (no login required)
  • http://www.jimspice.com jimspice

    Since we’re dealing with CSS3, why not include alpha?

    • http://twitter.com/NikkitaFTW Sara Vieira

      I didn’t add it because in the type of images I was dealing with the alpha would always be 1

  • 1076

    Very cool!
    I’ve been looking to create my own fully HTML5 color picker.
    I’m currently using a great prefab, but I’d like to develop a custom one to expand on the functionality. This will be a great help.

    Any tips on how to display a color range similar to Photoshop’s color picker? (without using images)

    • http://twitter.com/NikkitaFTW Sara Vieira

      I’m glad this helped.

      I think you should take a look at the source code from http://www.colorpicker.com/ , they use a combination of javascript for the hue and then a background color and a gradient on top that goes from black to transparent for displaying every single color in that hue

      • 1076

        Aye, that seems to be most people’s solution. And I suppose I could work with that as a Base64 encoded shade image.
        It might be the only way to get any real cross-browser compatibility.

        Thanks for that suggestion!

    • http://twitter.com/hauermateusz hauer mateusz

      cool. hope that we can we use this solution free :) ?

      • 1076

        Ha ha!
        Well, the app I’m adding a color picker to will be free, but since I’m tailoring a color picker TO my app, instead of building something more open than what is currently available, I’m not sure how good it would do to let other people use it.

        If it’s feasible, though, then sure!

        Though, someone else pointed me to Spectrum, which is a GREAT free color picker, if you want to check that out.
        http://bgrins.github.com/spectrum/

        1076

  • http://twitter.com/ersunnygupta AKHIL GUPTA

    very interesting and innovative and i changed the mouse cusrsor shape to crosshair so to point out the exact x,y coordinate elements :)

  • Lucas

    Very cool, Sara. Nice work. I would like to implement this on my site as well, however, I’ve run into a small problem. The getImageData function doesn’t seem to work all over the image. Only on about half the image. I’ve console.logged the XY, and RGB variables on click, and the RGB values are 0, however, the XY variables are getting a value. Any idea why this might be happening?

  • Dave

    Is there a way to have this act as a link with the RGB values in part of that link instead of displaying them below?

    ie- any time the mouse is clicked it acts as if a hyper link was pressed with the value of “href=”/trigger/1234?var=Red:255,Green:255,Blue:255″ where Red,Green,Blue are the values of red green and blue (out of 255).

  • Sherin Jose

    Not working in Google Chrome…Error found…Uncaught SecurityError: Failed to execute ‘getImageData’ on ‘CanvasRenderingContext2D’: The canvas has been tainted by cross-origin data.