How to go from x,y coordinates to unique RGB value?

Viewed 360

I am trying to generate a unique RGB value for each x,y coordinate on a screen (I am doing this in JS).

It is not important that each RGB value shows up at least once, but it is important that each RGB value that does show up is unique (not all colors need to show up, but there can be no duplicate colors).

I have seen many people recommend using HSL/HSV to ensure all colors are used, however since this is not necessary in my case I am wondering if there is a simpler way.

The method I have come up with is the following:

var x = event.pageX/window.screen.width;
var y = event.pageY/window.screen.height;
var z = 1-x-y;

var r = parseInt(x*255);
var g = parseInt(y*255);
var b = parseInt(z*255);

I convert the x and y coordinates to values between 0 and 1, get z from those two, and then multiply by 255 to go from values between 0-1 to 1-255.

Although this is functional, there are duplicate colors around x~0.5 and y~0.5 and it misses a sizable portion of the RGB color spectrum.

Does anyone know of a better way of doing this while still staying relatively simplistic?

1 Answers

Assuming that x and y fit in 12 bits, you get 24 bits, just the right number for three 8-bit colors. So this will generate a unique color for every pixel of a screen up to 4096x4096.

function xy_to_rgb(x,y) {
  var t = x&0xFFF | (y<<12)&0xFFF;

  return {
    r: t&0xFF,
    g: (t>>8)&0xFF,
    b: (t>>16)&0xFF
  };

}
Related