nerdErg

Canvas Color Picker

28 June 2019

Updated 2019 - still works!

color circle

I really quite liked the Color Sphere by Color Jack. However the code was a little, um, terse. Having a look at his code it looks like he uses the image as a reference and then computes the HSV values using the algorithm  that’s used to produce the picture - pretty cool.

But wouldn’t it be simpler to just pick the pixel in the image when you click?? Sure! but…​ you can’t, due to javascript limitations/security. Damn. Oh wait what about <canvas>?

So I did a little experiment and here is the result (sorry won’t work in IE8).

Oh, sorry I don't get Canvas yet
Canvas color picker example

So here is the script:

color-sphere.js
// use jQuery on page load to draw the canvas image
$(function () {
    var ctx = document.getElementById('canvas').getContext('2d');
    var img = new Image();
    img.src = 'media/show/280';
    img.onload = function () {
      ctx.drawImage(img, 0, 0);
    }
    $('canvas').bind('mousemove', function (event) {
      var x = event.offsetX;
      var y = event.offsetY;
      var ctx = document.getElementById('canvas').getContext('2d');
      var imgd = ctx.getImageData(x, y, 1, 1);
      var data = imgd.data;
      var out = $('#result');
      var hexString = RGBtoHex(data[0], data[1], data[2]);
      out.html("color is #" + hexString);
      out.attr("style", "background-color: #" + hexString + ";");
    });
  }
);

//from http://www.linuxtopia.org/online_books/javascript_guides/javascript_faq/rgbtohex.htm

function RGBtoHex(R, G, B) {
  return toHex(R) + toHex(G) + toHex(B)
}

function toHex(N) {
  if (N == null) return "00";
  N = parseInt(N);
  if (N == 0 || isNaN(N)) return "00";
  N = Math.max(0, N);
  N = Math.min(N, 255);
  N = Math.round(N);
  return "0123456789ABCDEF".charAt((N - N % 16) / 16) + "0123456789ABCDEF".charAt(N % 16);
}

and the HTML looks like this:

color.html
<h2>Canvas color picker example</h2>
<div>
  <canvas id="canvas" width="370" height="370">Oh, sorry I don't get Canvas yet</canvas>
</div> <span style="" id="result"></span>