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="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.

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

Apple Opts for AR over VR at WWDC

An Apple VR headset has been one of the most widely-rumored devices of the last few years, and it was finally settled a…

Exciting New Tools for Designers, June 2023

We’re halfway through 2023 already, and the number of incredible apps, tools, and resources for designers is mounting.

3 Essential Design Trends, June 2023

This month we are focusing on three trends within a bigger website design trend – different navigation menu styles and …

15 Best New Fonts, May 2023

The choices you make when selecting a typeface have more impact on your design than almost any other decision, so it’s …

10+ Best Tools & Resources for Web Designers and Agencies (2023 updated)

Having the ability to envision a tastefully designed website (i.e., the role creativity plays) is important. But being …

20 Best New Websites, May 2023

This month, there are tons of great new agency websites to get excited about. 3D animated prisms are a popular theme, a…

How to Find the Right White Label Website Builder for Your Agency

Web design agencies face a lot of obstacles in closing the deal with new clients. One of the most common ones is the ar…

Exciting New Tools For Designers, May 2023

There are hundreds of new tools for designers and developers released each month. We sift through them all to bring you…

3 Essential Design Trends, May 2023

All three of the website design trends here mimic something bigger going on in the tech space, from a desire to have mo…

10 Best AI Tools for Web Designers (2023)

It’s time to stop worrying if AI is going to take your job and instead start using AI to expand the services you can of…

10 Best Marketing Agency Websites (Examples, Inspo, and Templates!)

Marketers are skilled in developing strategies, producing visual assets, writing text with high impact, and optimizing …

15 Best New Fonts, April 2023

Fonts are a designer’s best friend. They add personality to our designs and enable fine typography to elevate the quali…