How to create a color picker with HTML5 Canvas

Default avatar.
March 21, 2013
How to create a color picker with HTML5 Canvas.

ThumbnailCreating 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="https://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.

Sara Vieira

Sara Vieira is a freelance Web Designer and Developer with a passion for HTML5/CSS3 and jQuery. You can follow her on twitter or check out her website.

Read Next

10+ Best Resources & Tools for Web Designers (2024 update)

Is searching for the best web design tools to suit your needs akin to having a recurring bad dream? Does each…

3 Essential Design Trends, April 2024

Ready to jump into some amazing new design ideas for Spring? Our roundup has everything from UX to color trends…

How to Plan Your First Successful Website

Planning a new website can be exciting and — if you’re anything like me — a little daunting. Whether you’re an…

15 Best New Fonts, March 2024

Welcome to March’s edition of our roundup of the best new fonts for designers. This month’s compilation includes…

LimeWire Developer APIs Herald a New Era of AI Integration

Generative AI is a fascinating technology. Far from the design killer some people feared, it is an empowering and…

20 Best New Websites, March 2024

Welcome to our pick of sites for March. This month’s collection tends towards the simple and clean, which goes to show…

Exciting New Tools for Designers, March 2024

The fast-paced world of design never stops turning, and staying ahead of the curve is essential for creatives. As…

Web Tech Trends to Watch in 2024 and Beyond

It hardly seems possible given the radical transformations we’ve seen over the last few decades, but the web design…

6 Best AI Productivity Apps in 2024

There’s no escaping it: if you want to be successful, you need to be productive. The more you work, the more you…

3 Essential Design Trends, February 2024

From atypical typefaces to neutral colors to unusual user patterns, there are plenty of new website design trends to…

Surviving the Leap from College to Real-World Design

So, you’ve finished college and are ready to showcase your design skills to the world. This is a pivotal moment that…

20 Mind-Bending Illusions That Will Make You Question Reality

Mind-bending videos. Divisive Images. Eye-straining visuals. This list of optical illusions has it all. Join us as we…