Skip to content

Instantly share code, notes, and snippets.

@patrickmmartin
Created October 22, 2018 20:36
Show Gist options
  • Save patrickmmartin/ebc6f4c157f313da55228aeb75e4a3e2 to your computer and use it in GitHub Desktop.
Save patrickmmartin/ebc6f4c157f313da55228aeb75e4a3e2 to your computer and use it in GitHub Desktop.
Javascript colour generation
<!DOCTYPE html>
<html>
<body>
<div id="colour">???<div>
<button type="button" onclick="start()">Start</button>
<script>
var i = 0;
// combines all 3 colours using the colour wheel's trapezoid shape
// more complex, but generates pure colours and pure binary mixes
// hence the complementary colours
function coloursHSL(it)
{
var sat = (it < 1000)?i/20:50;
var h = it % 360;
var s = sat;
var l = 50
return "hsl(" + h + ", " + s +"%, " + l + "% )";
}
// smoothly combines all 3 colours with a mixing derived from an angle +/- offset
// no pure colours, as a consequence but is smooth
function coloursTrig(it)
{
var mult = (it < 1270)?i/10:127;
var r = mult * (1 + Math.sin((( 00 + it) / 100) * Math.PI));
var g = mult * (1 + Math.sin((( 50 + it) / 100) * Math.PI));
var b = mult * (1 + Math.sin((( -50 + it) / 100) * Math.PI));
return "rgb(" + r + ", " + g +", " + b + ")";
}
function loop() {
i++;
var colour = coloursHSL(i);
// var colour = "hsl(180, 50%, 50%)"
document.getElementById("colour").innerHTML = colour;
document.body.style.backgroundColor = colour;
}
function start()
{
setInterval(loop, 5);
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment