Exploring HSB to RGB Color Conversion

JavaScriptJavaScriptBeginner
Practice Now

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

Introduction

In this lab, we will explore the HSB to RGB color conversion process using JavaScript. We will learn how to convert HSB color values to RGB format using a formula and convert the output to the appropriate range of values. By the end of the lab, you will have a better understanding of color models and how to work with them in JavaScript.


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-28377{{"`Exploring HSB to RGB Color Conversion`"}} javascript/data_types -.-> lab-28377{{"`Exploring HSB to RGB Color Conversion`"}} javascript/arith_ops -.-> lab-28377{{"`Exploring HSB to RGB Color Conversion`"}} javascript/comp_ops -.-> lab-28377{{"`Exploring HSB to RGB Color Conversion`"}} end

HSB to RGB Conversion

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

  • Open the Terminal/SSH and type node to start practicing coding.
  • Use the HSB to RGB conversion formula to convert to the appropriate format.
  • The input parameters should be in the range of H: [0, 360], S: [0, 100], B: [0, 100].
  • All output values should be in the range of [0, 255].

Here's the code that you can use to convert HSB to RGB:

const HSBToRGB = (h, s, b) => {
  s /= 100;
  b /= 100;
  const k = (n) => (n + h / 60) % 6;
  const f = (n) => b * (1 - s * Math.max(0, Math.min(k(n), 4 - k(n), 1)));
  return [255 * f(5), 255 * f(3), 255 * f(1)];
};

For example, if you want to convert the HSB color tuple (18, 81, 99) to RGB format, you can use the following code:

HSBToRGB(18, 81, 99); // [252.45, 109.31084999999996, 47.965499999999984]

Summary

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

Other JavaScript Tutorials you may like