Square hsb palette
by Alexander Shutov
HTML
<canvas id="palette"></canvas>
<input id="range" type="range" min="0" max="1" step="0.1" value="1"></input>
JavaScript
var range = document.getElementById('range');
range.oninput = function () {
drawPalette(parseFloat(this.value));
console.log(this.value);
};
var canvas = document.getElementById('palette');
var ctx = canvas.getContext('2d');
var radius = 100;
canvas.width = radius * 2;
canvas.height = radius * 2;
var cx = radius,
cy = radius;
function drawPalette(arg) {
for (var x = 0; x < canvas.width; x++) {
for (var y = 0; y < canvas.height; y++) {
var hue = Math.atan2(cy - y, cx - x) / Math.PI * 180;
if (hue < 0) hue += 360;
var saturation = Math.sqrt((cy - y) * (cy - y) + (cx - x) * (cx - x)) / radius;
var brightness = arg;
if (saturation <= 1) {
var color = hsbToRgb({
h: hue,
s: saturation,
b: brightness
});
ctx.fillStyle = 'rgb(' + color.r + ',' + color.g + ',' + color.b + ')';
ctx.fillRect(x, y, 1, 1);
}
}
}
}
function hsbToRgb(hsb) {
// Check values
if (hsb.h < 0 || hsb.h > 360 || hsb.s < 0 || hsb.s > 1 || hsb.b < 0 || hsb.b > 1) {
throw new Error('Unable to convert color: hue = ' + hsb.h + ', saturation = ' + hsb.s + ', brightness = ' + hsb.b + '.');
}
// Apply hue.
var hued;
if (hsb.h < 60) {
hued = {
r: 255,
g: Math.round(hsb.h / 60 * 255),
b: 0
};
} else if (hsb.h < 120) {
hued = {
r: Math.round((120 - hsb.h) / 60 * 255),
g: 255,
b: 0
};
} else if (hsb.h < 180) {
hued = {
r: 0,
g: 255,
b: Math.round((hsb.h - 120) / 60 * 255)
};
} else if (hsb.h < 240) {
hued = {
r: 0,
g: Math.round((240 - hsb.h) / 60 * 255),
b: 255
};
} else if (hsb.h < 300) {
hued = {
r:...