I'm using the YUI2 colour picker on a project to provide a theme/colour scheme changing functionality. I'm setting the default rgb value of each colour picker to the current rgb value of an element of the colour scheme.
The rgb value that the picker holds is fine, however the Hue Slider and Picker Slider are not updating to reflect this. Whenever the colour picker appears the hue and picker are set to 0 and ffffff respectively.
I've searched through the documentation and tried a few likely methods that might update the hue/picker slider appropriately, with no luck.
Any advice would be greatly appreciated
After some more searching and playing around I managed to come up with a solution. There are two steps to the process;
You need to compute the HSV (Hue, Saturation, Value) from the rgb value. This is done using the function rgbTohsv() below, which I got here. Its been modified from the original to account for the way the YUI HueSlider and PickerSlider expect input.
function rgbTohsv (rgb) {
var computedH = computedS = computedV = 0;
//remove spaces from input RGB values, convert to int
var r = parseInt( (''+rgb[0]).replace(/\s/g,''),10 );
var g = parseInt( (''+rgb[1]).replace(/\s/g,''),10 );
var b = parseInt( (''+rgb[2]).replace(/\s/g,''),10 );
r=r/255; g=g/255; b=b/255;
var minRGB = Math.min(r,Math.min(g,b));
var maxRGB = Math.max(r,Math.max(g,b));
// Black-gray-white
if (minRGB==maxRGB) {
computedV = minRGB;
return [0,0,Math.round(computedV*100)];
}
// Colors other than black-gray-white:
var d = (r==minRGB) ? g-b : ((b==minRGB) ? r-g : b-r);
var h = (r==minRGB) ? 3 : ((b==minRGB) ? 1 : 5);
computedH = 60*(h - d/(maxRGB - minRGB));
computedS = (maxRGB - minRGB)/maxRGB;
computedV = maxRGB;
return [(360-computedH)/2,Math.round(computedS*100),Math.round(computedV*100)];
}
Modifications:: The hue slider expects a value between 180-0, rather than the usual 0-360. As well as the shorter range it is also inverted so it goes from 180->0. The S and V values must be an integer between 0-100, whereas the original function returned 0-1.0 values. Both of these issues have been accounted for in the above function.
Next you need to set the hsv values of the colour picker., so where colourPicker is your initialised colour picker variable;
hsv = rgbTohsv(rgb);
colourPicker.hueSlider.setValue(hsv[0],0);
colourPicker.pickerSlider.setRegionValue(hsv[1],hsv[2]);
By default updating the hue slider and picker slider do an animation when updated, you can suppress this by adding a false
variable at the end of the method call.
colourPicker.hueSlider.setValue(hsv[0],0,true);
colourPicker.pickerSlider.setRegionValue(hsv[1],hsv[2], true);