New JavaScript and Processing.js blog with Postbit!

Processing.js blog: http://processing.postbit.com/

JavaScript blog: http://js.postbit.com/
Posted in Javascript Audio, Javascript Blog, Javascript Canvas, Processing Art, Uncategorized | Leave a comment

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:
Preview
color
Selected
color


HTML 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 = 'http://js.do/images/color-picker/color-picker-spectrum.png';

// 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;
  ctx.drawImage(img,0,0);
}

$('#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);
  $('#picked_color_rgb').html(rgb);
});

$('#canvas_picker').bind('click', function(event){
  $('#picked_color').css('background-color', rgb);
});
Posted in Javascript Canvas | Leave a comment