Search code examples
three.jshsl

Three.js use variable to set HSL background color


I am trying to set the renderer.setClearColor() to a new HSL color using a variable. It works if I define the variable directly, but when I try to change it by using another variable, I get this error:

THREE.Color: Unknown color hsl(color1[0], 96%, 95%)

here is the code I am using to try and just change the hue:

backgroundColor = new THREE.Color("hsl(0, 96%, 95%)");

function getColors(){
color1 = [];
color1h = (data[1] / 359);
color1s = (0.90);
color1l = (0.65);
color1.push(color1h, color1s, color1l);
backgroundColor = new THREE.Color("hsl(color1[0], 96%, 95%)");
}
...
renderer.setClearColor(backgroundColor);

Any advice would be appreciated!


Solution

  • I think the actual bug in the OP's code is that it's passing a variable as a string. Using template literal it should be:

    backgroundColor = new THREE.Color(`hsl(${color1[0]}%, 96%, 95%)`);
    

    I had this same issue, but it was caused by the hsl values being floats instead of integers. In other words I was passing something like hsl(45.356456%, 96%, 95%). I was able to fix it by just rounding the number to the nearest integer.

    backgroundColor = new THREE.Color(`hsl(${Math.round(color1[0])}%, 96%, 95%)`);