MCPcopy Create free account
hub / github.com/TheAlgorithms/JavaScript / rgbToHsv

Function rgbToHsv

Conversions/RgbHsvConversion.js:48–82  ·  view source on GitHub ↗
(red, green, blue)

Source from the content-addressed store, hash-verified

46 * @return The tuple of HSV-components.
47 */
48export function rgbToHsv(red, green, blue) {
49 if (red < 0 || red > 255) {
50 throw new Error('red should be between 0 and 255')
51 }
52
53 if (green < 0 || green > 255) {
54 throw new Error('green should be between 0 and 255')
55 }
56
57 if (blue < 0 || blue > 255) {
58 throw new Error('blue should be between 0 and 255')
59 }
60
61 const dRed = red / 255
62 const dGreen = green / 255
63 const dBlue = blue / 255
64 const value = Math.max(Math.max(dRed, dGreen), dBlue)
65 const chroma = value - Math.min(Math.min(dRed, dGreen), dBlue)
66 const saturation = value === 0 ? 0 : chroma / value
67 let hue
68
69 if (chroma === 0) {
70 hue = 0
71 } else if (value === dRed) {
72 hue = 60 * ((dGreen - dBlue) / chroma)
73 } else if (value === dGreen) {
74 hue = 60 * (2 + (dBlue - dRed) / chroma)
75 } else {
76 hue = 60 * (4 + (dRed - dGreen) / chroma)
77 }
78
79 hue = (hue + 360) % 360
80
81 return [hue, saturation, value]
82}
83
84export function approximatelyEqualHsv(hsv1, hsv2) {
85 const bHue = Math.abs(hsv1[0] - hsv2[0]) < 0.2

Callers 1

Calls

no outgoing calls

Tested by

no test coverage detected