Skip to content

Instantly share code, notes, and snippets.

@gorbiz
Created June 19, 2016 14:14
Show Gist options
  • Save gorbiz/99a6e9051cf54d1321672f0a7840af50 to your computer and use it in GitHub Desktop.
Save gorbiz/99a6e9051cf54d1321672f0a7840af50 to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<input id="color" type="color" value="#ff0000" />
<script>
function hexToRgb(hex) {
var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
return result ? {
r: parseInt(result[1], 16),
g: parseInt(result[2], 16),
b: parseInt(result[3], 16)
} : null;
}
function hsl2rgb (h, s, l) {
var r, g, b, m, c, x
if (!isFinite(h)) h = 0
if (!isFinite(s)) s = 0
if (!isFinite(l)) l = 0
h /= 60
if (h < 0) h = 6 - (-h % 6)
h %= 6
s = Math.max(0, Math.min(1, s / 100))
l = Math.max(0, Math.min(1, l / 100))
c = (1 - Math.abs((2 * l) - 1)) * s
x = c * (1 - Math.abs((h % 2) - 1))
if (h < 1) {
r = c
g = x
b = 0
} else if (h < 2) {
r = x
g = c
b = 0
} else if (h < 3) {
r = 0
g = c
b = x
} else if (h < 4) {
r = 0
g = x
b = c
} else if (h < 5) {
r = x
g = 0
b = c
} else {
r = c
g = 0
b = x
}
m = l - c / 2
r = Math.round((r + m) * 255)
g = Math.round((g + m) * 255)
b = Math.round((b + m) * 255)
return { r: r, g: g, b: b }
}
// color picker code
document.getElementById('color').onchange = function(e) {
color = hexToRgb(e.target.value);
// we want 0 to 1023
color.r = (color.r + 1) * 4 - 1;
color.g = (color.g + 1) * 4 - 1;
color.b = (color.b + 1) * 4 - 1;
console.log(color);
fetch('http://192.168.1.115/color?red=' + color.r + '&green=' + color.g + '&blue=' + color.b)
.then(function(response) {
console.log(response);
});
};
// move mouse cursor X-wise to change HUE
var last = Date.now();
document.onmousemove = function(e) {
if (Date.now() - last < 80) return; // limit request frequency (100 gives max 10 / second)
last = Date.now();
var x = e.clientX;
var y = e.clientY;
var color = hsl2rgb(x, 255, 50);
// we want 0 to 1023
color.r = (color.r + 1) * 4 - 1;
color.g = (color.g + 1) * 4 - 1;
color.b = (color.b + 1) * 4 - 1;
fetch('http://192.168.1.115/color?red=' + color.r + '&green=' + color.g + '&blue=' + color.b)
.then(function(response) {
console.log(response);
});
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment