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

15 Best New Fonts, July 2024

Welcome to our monthly roundup of the best fonts we’ve found online in the last four weeks. This month, there are fewer…

20 Best New Websites, July 2024

Welcome to July’s round up of websites to inspire you. This month’s collection ranges from the most stripped-back…

Top 7 WordPress Plugins for 2024: Enhance Your Site's Performance

WordPress is a hands-down favorite of website designers and developers. Renowned for its flexibility and ease of use,…

Exciting New Tools for Designers, July 2024

Welcome to this July’s collection of tools, gathered from around the web over the past month. We hope you’ll find…

3 Essential Design Trends, July 2024

Add some summer sizzle to your design projects with trendy website elements. Learn what's trending and how to use these…

15 Best New Fonts, June 2024

Welcome to our roundup of the best new fonts we’ve found online in the last month. This month, there are notably fewer…

20 Best New Websites, June 2024

Arranging content in an easily accessible way is the backbone of any user-friendly website. A good website will present…

Exciting New Tools for Designers, June 2024

In this month’s roundup of the best tools for web designers and developers, we’ll explore a range of new and noteworthy…

3 Essential Design Trends, June 2024

Summer is off to a fun start with some highly dramatic website design trends showing up in projects. Let's dive in!

15 Best New Fonts, May 2024

In this month’s edition, there are lots of historically-inspired typefaces, more of the growing trend for French…

How to Reduce The Carbon Footprint of Your Website

On average, a web page produces 4.61 grams of CO2 for every page view; for whole sites, that amounts to hundreds of KG…

20 Best New Websites, May 2024

Welcome to May’s compilation of the best sites on the web. This month we’re focused on color for younger humans,…