JavaScript HSL to RGB Conversion

JavaScriptJavaScriptBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In this lab, we will delve into the world of JavaScript programming and learn about HSL to RGB conversion. You will be introduced to the HSL to RGB conversion formula, and how to use it to convert HSL color tuples to RGB format. By the end of this lab, you will have gained a deeper understanding of how to work with color in JavaScript and how to manipulate HSL values to create beautiful color schemes.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL javascript(("`JavaScript`")) -.-> javascript/BasicConceptsGroup(["`Basic Concepts`"]) javascript/BasicConceptsGroup -.-> javascript/variables("`Variables`") javascript/BasicConceptsGroup -.-> javascript/data_types("`Data Types`") javascript/BasicConceptsGroup -.-> javascript/arith_ops("`Arithmetic Operators`") javascript/BasicConceptsGroup -.-> javascript/comp_ops("`Comparison Operators`") subgraph Lab Skills javascript/variables -.-> lab-28378{{"`JavaScript HSL to RGB Conversion`"}} javascript/data_types -.-> lab-28378{{"`JavaScript HSL to RGB Conversion`"}} javascript/arith_ops -.-> lab-28378{{"`JavaScript HSL to RGB Conversion`"}} javascript/comp_ops -.-> lab-28378{{"`JavaScript HSL to RGB Conversion`"}} end

Convert HSL to RGB using JavaScript

To convert a color tuple in HSL format to RGB, follow these steps:

  1. Open the Terminal/SSH and type node to start practicing coding.
  2. Use the HSL to RGB conversion formula to convert the color tuple to the appropriate format.
  3. Ensure that the input parameters are within the following ranges: H: [0, 360], S: [0, 100], L: [0, 100].
  4. The output values should be within the range [0, 255].

Here is the JavaScript code for the HSL to RGB conversion formula:

const HSLToRGB = (h, s, l) => {
  s /= 100;
  l /= 100;
  const k = (n) => (n + h / 30) % 12;
  const a = s * Math.min(l, 1 - l);
  const f = (n) =>
    l - a * Math.max(-1, Math.min(k(n) - 3, Math.min(9 - k(n), 1)));
  return [255 * f(0), 255 * f(8), 255 * f(4)];
};

To use the function, provide the H, S, and L values as arguments:

HSLToRGB(13, 100, 11); // [56.1, 12.155, 0]

Summary

Congratulations! You have completed the HSL to RGB lab. You can practice more labs in LabEx to improve your skills.

Other JavaScript Tutorials you may like