Canvas Color Picker

This demo uses <canvas> element and reads RGB color value from the pixel selected with mouse. The script creates an img object and reads an image from url. Then it copies the image to the canvas element and binds to the "mousemove" event a function that reads the RGB color value from each pixel.

Pick a color:
MouseOver color code:

Pick a color: <canvas id="canvas_picker"></canvas>
MouseOver color code: <span id='picked_color_preview'>Preview</span>
<span id='picked_color_rgb'>Selected</span>
<div id='picked_color' style='width: 112px; height: 100px; border: 1px solid black;'>
var img = new Image();
img.src = '';

// Copy image (img) to canvas
img.onload = function() {
  var c = document.getElementById('canvas_picker');
  var ctx = c.getContext('2d');
  c.width  = img.width;
  c.height = img.height;

$('#canvas_picker').bind('mousemove', function(event){
  var x = event.pageX - event.currentTarget.offsetLeft;
  var y = event.pageY - event.currentTarget.offsetTop;
  var ctx = document.getElementById('canvas_picker').getContext('2d');
  var img_data = ctx.getImageData(x, y, 1, 1).data;
  var R = img_data[0];
  var G = img_data[1];
  var B = img_data[2];
  var rgb = 'rgb('+R+','+G+','+B+')';
  $('#picked_color_preview').css('background-color', rgb);

$('#canvas_picker').bind('click', function(event){
  $('#picked_color').css('background-color', rgb);

About Rodrigo Siqueira

Software developer and director at Insite ( I create Internet tools like: online forums, chat rooms, email marketing software, task management and chatter bots. I love to code in JavaScript, jQuery, Node.js and Perl.
This entry was posted in Javascript Canvas. Bookmark the permalink.