New JavaScript and Processing.js blog with Postbit!

Processing.js blog:

JavaScript blog:
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:

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);
Posted in Javascript Canvas | Leave a comment