Search code examples
javascriptcolorsthree.jshsl

Passing variables into HSL color values in Three.JS


I currently have 2 HSL colors set in my code:

scene.background = new THREE.Color("hsl(0, 100%, 50%)");
var light = new THREE.AmbientLight("hsl(180, 100%, 50%)");

I'm trying to pass a variable for 'hue' from my CSS in.

When I run this code, I'm able to see the 2 color variables I have defined in my CSS, which are 0 and 180 respectively:

var style = getComputedStyle(document.body);
console.log(style.getPropertyValue("--color-accent-hue")); // get accent hue color
console.log(style.getPropertyValue("--color-accent-hue-inverse")); // get accent hue inverse color

At the beginning of my code, I defined these as JS variables like this:

const colorAccentHue = style.getPropertyValue('--color-accent-hue');
const colorAccentHueInverse = style.getPropertyValue('--color-accent-hue-inverse');

then tried to call them within my init() function like this:

scene.background = new THREE.Color("hsl(colorAccentHue, 100%, 50%)");
var light = new THREE.AmbientLight("hsl(colorAccentHueInverse, 100%, 50%)");`

But I get nothing. Where am I going wrong here?


Solution

  • You can use template literals (or string concatenation).

    scene.background = new THREE.Color(`hsl(${colorAccentHue}, 100%, 50%)`);
    var light = new THREE.AmbientLight(`hsl(${colorAccentHueInverse}, 100%, 50%)`);