JSFiddle - React, Tailwind, and code Playground

by Derek Leung

HTML

Choose a color: <input type="color" value="#FF0000">
<div id="color" style="background: rgb(255, 0, 0)"></div>
<div id="complement" style="background: rgb(0, 169, 51)"></div>

CSS

div{
    width: 50px;
    height: 50px;
}

JavaScript

$("input").change(function(){
    var rgb = hexToRgb(this.value), ryb = rgb2ryb(rgb);
    console.log(ryb);
    $("#color").css("background", "rgb(" + rgb.join(",") + ")");
    var complementRYB = ryb.map(function(n){ return 255 - n; }),
        complementRGB = ryb2rgb(complementRYB).map(function(n){
            return n|0;
        });
    $("#complement").css("background", "rgb(" + complementRGB.join(",") + ")");
    
});


function hexToRgb(hex) {
    var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
    return result ? [
        parseInt(result[1], 16),
        parseInt(result[2], 16),
        parseInt(result[3], 16)
    ] : null;
}

//found on the web
function rgb2ryb(color) {
    var r = color[0], g = color[1], b = color[2];
    // Remove the whiteness from the color.
    var w = Math.min(r, g, b);
    r -= w;
    g -= w;
    b -= w;

    var mg = Math.max(r, g, b);

    // Get the yellow out of the red+green.
    var y = Math.min(r, g);
    r -= y;
    g -= y;

    // If this unfortunate conversion combines blue and green, then cut each in
    // half to preserve the value's maximum range.
    if (b && g) {
        b /= 2.0;
        g /= 2.0;
    }

    // Redistribute the remaining green.
    y += g;
    b += g;

    // Normalize to values.
    var my = Math.max(r, y, b);
    if (my) {
        var n = mg / my;
        r *= n;
        y *= n;
        b *= n;
    }

    // Add the white back in.
    r += w;
    y += w;
    b += w;

    // And return back the ryb typed accordingly.
    return [r, y, b];
}

/**
 * Convert a red-yellow-blue system to a red-green-blue system.
 */
function ryb2rgb(color) {
    var r = color[0], y = color[1], b = color[2];
    // Remove the whiteness from the color.
    var w = Math.min(r, y, b);
    r -= w;
    y -= w;
    b -= w;

    var my = Math.max(r, y, b);

    // Get the green out of the yellow and blue
    var g = Math.min(y, b);
    y -= g;
    b -= g;

    if (b && g) {
        b *= 2.0;
        g *=...