Colory – A small JavaScript Class for HEX to RGB, RGB to HEX conversion and Gradient Color List Building

This is a small JavaScript pseudo-class that I use to quickly convert HEX to RGB colour format and RGB back to HEX and also create an array of gradient colours between two colours.

This guide is just a convenient place for me to store this reference for future use. I hope you can get some use out of it too.

Methods

  • rgbToHex(r, g, b) – returns String – A hexadecimal colour.
  • hexToRgb(hex) – returns [Number, Number, Number] – A red, green and blue (RGB) array of numbers from 0-255
  • generateColorGradient(colorStart, colorEnd, steps) – returns [[Number, Number, Number], ...] – An array of RGB colours by a set step.

The Code – Colory Class in JavaScript

Detailed Documentation

rgbToHex(r, g, b)

Converts RGB color (Red, Green Blue) to hexadecimal colour.

If your rgb is in an array you can use the spread operator. e.g. color().rgbToHex(…rgb)

Parameters

  • {Number} r – red 3-digit colour code.
  • {Number} g – green 3-digit colour code.
  • {Number} b – blue 3-digit colour code.

Returns

String – Hexadecimal string.

hexToRgb(hex)

Converts Hexadecimal colour to RGB

Parameters

  • {String} hex – hexadecimal colour as a string.

Returns

[Number, Number, Number] – RGB number set for the target colour.

generateColorGradient(colorStart, colorEnd, steps)

Generates a colour gradient based on the start and end colours at a set number of steps. Start and end colours can be added as hexadecimal string values or RGB number values within an array.

Parameters

  • {String|[Number, Number, Number]} colorStart – Start colour as Hexadecimal string or set of 3 RGB 3-digit number series.
  • {String|[Number, Number, Number]} colorEnd – Start colour as Hexadecimal string or set of 3 RGB 3-digit number series.
  • {Number} steps – total number of steps to break down into.

Returns

{[[Number, Number, Number], …]} – A 2d array of RGB number arrays at the set step length.

Conclusion

This is mostly used for solo projects, often in Google Apps Script. As such, I have not included any error handling. This also increased performance because the code has less work to do. The JS doc tooltips are enough for me here and you could deduce most errors from natural errors caused in JavaScript.

My recommendation is to only add the methods that you believe you are going to use and remove the rest. No need to bloat out your own project.

Having said that, let me know if there are some other methods you would like to see in the class and I will have a crack at adding them in.

 

~ Yagi