Saturday, 25 January 2014

How to create a color picker with HTML5 Canvas

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.

No comments:

Post a Comment